cPanel & WHMEmail

How to delete emails older than X days from a cPanel server

Sometimes you may want to delete emails that are older than a set amount of days from your cPanel server leaving the emails which are not older than this value in place on the server. The best way to achieve this is by creating a simple bash script on the server and then running the file from a console or by adding a cron job into cPanel to run it automatically every so often.

Log into the cPanel Server with the email account from which you want to delete messages. You need to be the root user or a user with root privileges. Edit the script below to replace the default values.

cPanel delete emails older than X days

#!/bin/bash
 IFS=$cpanel_username=cPanel_user_name domain=first2host.co.uk username=emailuser cd /home/${cpanel_username}/mail/${domain}/${username} find -P /home/${cpanel_username}/mail/${domain}/${username}/* -mindepth 1 -maxdepth 1 -mtime +730 | while read old; do echo “Deleting ${old}…” rm -rf “${old}” done

Edit the following values to reflect your cPanel server and email account details

  • cpanel_username
    • The cPanel account the email account is deployed to.
  • domain
    • The domain name the email account is deployed to.
  • username
    • the email account username without the @domain.com
  • -mtime
    • This is the value to change to delete emails older than X amount of days. In our example it’s set to +730 which is two years. For one year you would change this to -mtime +365

Issue the below command and paste the script you have edited into the file. Remember to save the file and close after you have pasted the script into it.

yum install nano -y; nano removeemails.sh

Now you can either run this script from the console you are already logged into by issuing this command;

sh removeemails.sh

Or you can set this to run as a cron job from the cPanel account. It’s best to move the script to the user’s home directory and then enter the absolute path to the script in the cron job. The path will be similar to this. You should set this to run once a day or once a week for a permanent solution.

/home/cPanelUser/removeemails.sh

Related Articles

Leave a Reply

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

Back to top button