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 server with the email account on from which you want to remove messages from. You need to be the root user or a user with root privileges
With the script below copy and paste it into a notepad document on your computer so you can edit it with ease.
#!/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 its 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 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
How was this article? – How to delete emails older than X days from a cPanel server
More from cPanel
Shared cPanel Servers – Distributing the cost of cPanel and other software licenses
The cost of software that runs on servers is at a record high. In many cases where cPanel is used …
How To Install Memcached PHP Cache In cPanel Servers
Memcached is an in-memory caching function that allows fast access and low-latency caching for PHP applications. Used by major companies …
How To Install A Cloudflare Origin SSL Certificate In cPanel
Free SSL Certificates from places like cPanel or Let's Encrypt are great. When Let's Encrypt first introduces free SSL Certificates …