Delete Old Emails and Notify User

ADMIN="admin@domain.com" # Admin email

DOMAIN="domain.com" # Domain name

HEADER="The emails listed has been moved to trash, and will be deleted on the 31st December every year" 

FOOTER="This is an automated email generated through a script, please find the script details at 'https://wiki.twcloud.tech/books/linux/page/delete-old-emails-and-notify-user'"

REMOVE_FILE_AGE=60 # File age to remove in days

USER="user" # Username used to login to the hosting account

TRASH_FOLDER="/home/$USER/trashed_emails/" # Trash folder with trailing slash

# Getting email information

[ -z "$1" ] && echo "Email user parameter missing" && exit 1

[ ! -d "/home/$USER/mail/$DOMAIN/$1/cur" ] && echo "Email not found" && exit 1

# Declarations

declare -A emails

for file in $(find "/home/$USER/mail/$DOMAIN/$1/cur" -type f -mtime +${REMOVE_FILE_AGE} -print); do

 if [ ! -f "$file" ]; then

 continue

 fi

 to="$1@$DOMAIN"

 from=`cat "$file" | grep -m 1 "^From\:\s\+" | sed 's/From\:\ //'`

 d=`cat "$file" | grep -m 1 "^Delivery-date\:\s\+" | sed 's/Delivery-date\:\ //'`

 subject=`cat "$file" | grep -m 1 "^Subject\:\s\+" | sed 's/Subject\:\ //'`

 # Send empty "$to" to admin

 [[ -z "$to" ]] && to="$ADMIN"

 # Construct email message

 [[ -z "${emails[$to]}" ]] && emails[$to]="$HEADER"

 emails[$to]="${emails[$to]}\n\nFrom: $from\nDate: $d\nSubject: $subject"

 # Move emails to trash

 mv "$file" "$TRASH_FOLDER"

done

# Notify email users that the emails are sent to trash

for k in "${!emails[@]}"; do

 echo -e "${emails[$k]}\n----------\n$FOOTER" | mail -s "Inbox Cleared" -c "$ADMIN" $k

done

