Delete old emails or just old junk emails for one or all users
I have created a nice script that deletes old emails for either a single user or all users.
It can also handle junk/spam emails only - which will also help to keep the account space usage down.
Usage examples:
A single user, with emails a year or older:
sh ./delete_old_emails.sh someuser 12
A single user, with junk email to delete, 3 months or older
sh ./delete_old_emails.sh anotheruser 3 junk
All users, with junk email to delete, 6 months or older
sh ./delete_old_emails.sh all 6 junk
This can easily be set to run using CRON.
#!/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.noah.hearle.com/cpanel-delete-old-emails/ #
# #
# Usage: sh ./delete_old_emails.sh #
# #
####################################################################
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 '
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 '
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 '
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 '
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"
Please sign in to leave a comment.
Comments
0 comments