Another handy script that I originally created in 2014, but updated to perform some sanity checks. This script will check for all files older than x months, or just targeting the junk emails, and permanently delete these emails.
#!/bin/sh
####################################################################
# #
# DELETE OLD EMAILS #
# #
# Coded by Noah Hearle, Design Extreme #
# https://designextreme.com #
# #
# Created: 2014/03/29 #
# Modified: 2021/10/14 #
# #
# Delete old emails for particular users or all users #
# #
# Post your comments at: #
# https://blog.nahoo.co.uk/cpanel-delete-old-emails/ #
# #
# Usage: sh ./delete_old_emails.sh <user> <age in months> <junk> #
# #
####################################################################
user=$1
age=$2
junk=$3
this=$(readlink -f $0)
if [ ! -n "$user" ] && ! [[ "$age" =~ ^[0-9]+$ ]]; then
echo -e "\e[38;5;202mError:\e[0m Please enter the user and the age in months"
echo 'Usage: sh ./delete_old_emails.sh <user> <age in months> <junk>'
exit
fi
if [ ! -n "$user" ]; then
echo -e "\e[38;5;202mError:\e[0m Please enter the user"
echo 'Usage: sh ./delete_old_emails.sh <user> <age in months> <junk>'
exit
fi
if ! [[ "$age" =~ ^[0-9]+$ ]]; then
echo -e "\e[38;5;202mError:\e[0m Please enter the age in months"
echo 'Usage: sh ./delete_old_emails.sh <user> <age in months> <junk>'
exit
fi
if [ "$age" -lt 2 ]; then
echo -e "\e[38;5;202mError:\e[0m Please enter an age of 2 or more months"
echo 'Usage: sh ./delete_old_emails.sh <user> <age in months> <junk>'
exit
fi
if [[ "$user" == '*' ]] || [[ "$user" == 'all' ]]; then
for directory in $(getent passwd | cut -d: -f6); do
user=$(sed -r 's#^/home/([^/]+)/?.*$#\1#' <<< $directory)
if [ ! -f "/var/cpanel/users/$user" ]; then
continue;
fi
sh $this $user $age $junk
done
exit
fi
if [ ! -f "/var/cpanel/users/$user" ]; then
echo -e "\e[38;5;202mError:\e[0m The user: $user doesn’t exist"
exit
fi
cd /home/
if [ -n "$junk" ]; then
find -P /home/$user/mail/*/*/\.{Junk,spam}/* -mindepth 1 -maxdepth 1 -mtime +$(($age * 31)) -delete
echo -e "\e[38;5;118mSuccess:\e[0m Removed old junk emails for user: \e[1m$user\e[0m older than $age months"
exit
fi
find -P /home/$user/mail/*/*/* -mindepth 1 -maxdepth 1 -mtime +$(($age * 31)) -delete
echo -e "\e[38;5;118mSuccess:\e[0m Removed old emails for user: \e[1m$user\e[0m older than $age months"
To run this, just check within the code as examples are given here:
sh ./delete_old_emails.sh <user> <age in months> <junk>
Having the user set to all or * will run it for all users on the server. The third argument just needs to exist for it to target junk.
Last updated on