Digital Media Insights for Business Owners

cPanel Erase Emails older than X amount of days – Tutorial

If you are a Linux admin or if you are hosting in a LAMP environment and you would like to delete emails from a particular Cpanel account without having to do it manually, you should do so directly via SSH.

The Problem:

The problem is that sometimes you want to only delete the emails that have some longevity. In other words, you may desire to delete only those emails that are older than x number of days. So how do you do that?

The Solution:

The solution is pretty simple. We are going to be using the find command from terminal.

So first, log into your server via ssh using terminal. Once there, locate the account that holds the emails in question. These accounts are usually located at: /home/name_of_account/mail/domain_name/

Use “cd” to go into the email account that you are about to delete emails from. You’ll see several folders, and in specific you’ll use two: /new and /cur

These two folders hold the emails for that particular account.

Now you can run the command that will list the emails that you want deleted. Please note, we are not deleting them just yet, we want to list them first to make sure we are finding the right ones.

find /home/name_of_account/mail/domain.com/username/new -mtime +5 -type f -ls

Great that will show you the emails that you are about to delete in a list. Check them and make sure they are the ones you want to delete and then run the final command:

find /home/name_of_account/mail/domain.com/username/new -mtime +5 -type f -delete

Also do the same by replacing /new with /cur as below:

find /home/name_of_account/mail/domain.com/username/cur -mtime +5 -type f -delete

So what is this command doing? First it finds in the given directory(/cur) the files (-type f) with a modified time in days (-mtime) of more than 5 (+5), then it deletes them.

Of course you can change the modified time to any number that you want, in this example I have used five days but of course you could use (+30) for a month or (+365) for a year, etc.

Word of Caution

I am using here the absolute path to the files for listing and also for deleting. That is important because once you list them and you see that they are the ones that you need to delete, then you can be certain that what you are about to delete is exactly in that path. If you instead use a relative path, for example if you are in the folder that you want to delete and you refer to it with a dot (.) when you delete you may end up in a different folder deleting the wrong information. Also, this can happen when using slash(/) or when using (~/) – so be careful not to skip the step of listing first, then deleting.

There you have it. That’s it. Please don’t hesitate to comment below if you found this helpful.

Until next time.

Say: "Hola" to your new clients.

Follow us on Social Media for more Tips & Tricks.

Other Posts You May Enjoy