How to delete SPAM / Junk mails automatically on cPanel servers

A few days ago I was looking for a way to delete spam junk mails automatically for all user accounts on a cPanel server, and I’ve found there is not a built in solution on cPanel or WHM software.

Unfortunately, cPanel doesn not include any way to automatically purge junk email messages. I guess they haven’t built such a feature maybe for the simple reason that sometimes we all get valid / legitimate emails in our junk / spam folder.

delete junk emails automatically on cpanel

However, this doesn’t happen all the time, and if you have lot of websites and you want to get rid of tons of GB of disk space used by junk emails, you can use this handy script I’ve found. This cool script does all the job perfectly, keeping your SPAM / junk emails deleted.

You can setup a cron to delete this mails once a month to keep your cPanel servers free of any junk mails. Let’s start.

Create the file:

nano -w /usr/local/bin/

Then paste this inside:

SPAMLIST=`find /home/*/mail/*/*/.Junk/cur/ -type f -mtime +30`

for list in ${SPAMLIST[@]}
    rm -fv $list;
    #echo $list

Save the file and assign execution permissions:

chmod +x /usr/local/bin/

The -mtime +30 is used to specify how old must be the files to be deleted, this means it will only delete files lder than 30 days, you can tweak this as you wish.

If you with only to know if you have files but not delete them, uncommend #echo $list and comment #rm -fv $list; lines.

You can setup this script to be run once a month or week, as you like. In this example we will run the command every 1st of each month at 00 hs:


crontab -e

Then paste this at the end of the file:

0 0 1 * * /usr/local/bin/

That’s all, now you’ve successfully setup a monthly cron to delete all your junk emails automatically for all your cPanel accounts.

Do you know other ways to delete junk emails massively on cPanel servers? Please share your knowledge with us.

About the Author: Santiago Borges

Experienced Sr. Linux SysAdmin and Web Technologist, passionate about building tools, automating processes, fixing server issues, troubleshooting, securing and optimizing high traffic websites.

Leave a Reply

Your email address will not be published. Required fields are marked *