Delete all emails older than 6 months with Cronjob in cPanel

Delete all emails older than 6 months with Cronjob in cPanel

Here is how to delete all emails older than 6 months from cPanel using a cronjob.

First, we need to know the exact location where emails are stored. On cPanel, emails are stored in 3 folders:

  • new – incoming emails are received in this folder
  • cur – all emails that are read by mail client
  • tmp – processed emails for delivery purpose

In cPanel these folders are located in the following path: /home/USERNAME/mail/DOMAIN/EMAIL/

  • So, for a single email account we would want to check and remove files in /home/USERNAME/mail/DOMAIN/EMAIL/cur
  • For all email accounts under a single domain name: /home/USERNAME/mail/DOMAIN/*/cur
  • For all email accounts under all domain names for a single user: /home/USERNAME/mail/*/*/cur
  • And for all email accounts under all cPanel users: /home/*/mail/*/*/cur

Now that we know the path where emails are stored, we can use one of these 2 methods to automatically delete emails older than X number of days.

1. Using Find and Cronjob

The following command will list and remove all emails older than 6 months (180 days):

CentOS:

find /home/USERNAME/mail/DOMAIN/*/cur -type f -mtime +180 -exec rm {} \;

Ubuntu:

find /home/USERNAME/mail/DOMAIN/*/cur -type f -mtime +180 -delete

Using your favorite text editor create a new file and put the above ☝️ command in it:

nano remove-old-emails.sh

then make it executable:

chmod +x remove-old-emails.sh

or

chmod 755 remove-old-emails.sh

Now to create a cronjob:

crontab -e
0 0 1 * * /root/remove-old-emails.sh > /dev/null 2>&1
:wq

then list all cronjobs to check if the newly created cronjob was added successfully:

crontab -l

In the above example cronjob will execute on the 1st day of every month and remove all emails older than 6 months (180 days).

2. Using tmpwatch

tmpwatch is an amazingly useful tool that removes files which haven’t been accessed for a period of time.

First, check if tmpwatch is installed on your system, if not, install it.

CentOS:

yum install tmpwatch -y

Ubuntu:

apt install tmpreaper

To use tmpwatch we need to specify the location where email files are stored and which files to remove (by default tmpwatch removes folders also).

  • d – for days,
  • h – for hours,
  • m – for minutes,
  • s – for seconds.

An example cronjob to remove files everyday at 1AM:

0 1 * * * /usr/sbin/tmpwatch -m 180d --nodirs /home/USERNAME/mail/DOMAIN/*/cur

Thats All.

Written by
Stefan Pejcic
Join the discussion

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.