Cronjob to delete all mails older than one month from server.

By -

Before starting with the cronjob script we will know the locations where the emails stored in server. Exactly there have three folders for managing received mails on a cPanel based server. That are cur, new, tmp. The main differences between these three are

new : This is the folder where all emails are first received.
cur : Is the folder having emails that are opened/read by mail client.
tmp : Is the folder contains processed emails for delivery purpose.

To clear older mails from server means, remove mail related files from cur folder under mails/ directory and all other mail user directory. There are cur and new directories under the mail folder for cPanel default mail and also the same in each users domain directory.
ie /home/username/mail/domain.com/***/cur Here *** represents each mail user folder.(admin/ for [email protected])

STEP 1
For simplicity, create an executable bash file under any where(here I’m selected location under root) and place the script to remove older mails. Here I’m using the find command to find and remove mails which are older than 30 days (-mtime switch for finding mails older than 30 days. For more about find command refer this link ).

[root@EcLinux]# touch mailcleaner.sh

Edit the file using your favorite file editor

 [root@EcLinux]# vim mailcleaner.sh
 find /home/username/mail/yourdomain.com/*/cur -type f -mtime +30 -exec rm -f {} ;
 :wq

Then change that file to an executable one. (ie file permission to 755)

 [root@EcLinux]# chmod 755 /root/mailcleaner.sh

STEP 2
Next step is to set the cronjob under root(for setting a cronjob refer this link ). Here I’m setting the cron job to run every 1 day of the month.

[root@EcLinux]# crontab -e
 0 0 1 * * /root/mailcleaner.sh > /dev/null 2>&1
 :wq

[root@EcLinux]# crontab -l : To list all cronjobs.

In this case the file mailcleaner.sh will execute first day of every month and remove all emails older than 30days.

Thank you.

Myself Arunlal, working as an administrator for both Linux and Windows servers. I am interested in Blogging, learning new things and technologies etc. I'm posting some interesting technical stuffs from my working experience. Let me know your suggestions as comment.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current day month ye@r *