How to erase old emails from Junk/Trash folders, cPanel


Most solutions online show how to erase emails based on the date they were received. Usually this is based on either the modification time of the file or the sent/received dates in the email’s headers. Here’s how to erase email based on how long it as been in a particular location, effectively cloning the behavior of Gmail.

The key here is using the “change time” or ctime of the file rather than the “modification time.” The mtime of a file is updated when the contents of the file are changed. On the other hand, the ctime is updated any time even the meta data of the file has been changed – like the file location or permissions.

The email files can be found using the find command’s -ctime option like this:
find ~/mail/domain.tld/*/.{Trash,Junk}/{cur,new}/ -ctime +30 -type f

This one liner will list all of the files (-type f) in the Trash and Junk’s cur and new folders that have not been changed within the last 30 days (-ctime +30).

Finally, to make this find command perform the action we want, we can add the “-delete” flag, like so:
find ~/mail/domain.tld/*/.{Trash,Junk}/{cur,new}/ -ctime +30 -type f -delete

That command will only run once, of course, so you might want to set up a cron job that runs it periodically.

This method is adapted from Kerkados’ article that uses the mtime with find.