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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | #!/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.