How to delete all Trash, Spam and Junk on a cPanel server

So here is an easy way to delete all Junk, Spam and Trash from all accounts under /home on a cPanel server, this command will delete anything that’s older than 30 days, you can actually change that to whatever you want; you will need root access to the server.

Let’s create a new bash script:

nano /root/delete_all_junk.sh

Now paste the following into the newly created file, and then save and exit:

#!/bin/bash
MAILDIRS=$(find /home/*/mail/*/* -maxdepth 0 -type d)
INBOXFOLDERS=(.Trash .Junk .Spam .Low\ Priority .cPanel\ Reports)
for basedir in $MAILDIRS; do
for ((i = 0; i < ${#INBOXFOLDERS[*]}; i++)); do
for dir in cur new; do
[ -e “$basedir/${INBOXFOLDERS[$i]}/$dir” ] && (
echo “Processing $basedir/${INBOXFOLDERS[$i]}/$dir…”
find “$basedir/${INBOXFOLDERS[$i]}/$dir/” -type f -mtime +30 -delete
)
done
done
done
/scripts/generate_maildirsize –verbose –allaccounts –force –confirm

Let’s make the newly created file executable:

chmod +x /root/delete_all_junk.sh

Then you can simply execute the file and it will do some clean up:

sh /root/delete_all_junk.sh

To change the amount of days look at the following line:

find “$basedir/${INBOXFOLDERS[$i]}/$dir/” -type f -mtime +30 -delete

and change the 30 for something else, depending on what you want.

This works great should you ever need to do a clean up of this sort, you can also create a cron job to clean up every once in a while and if you want to skip the trash and only delete Junk and Spam folder’s contents then just remove .Trash from the third line.