Skip to content

Instantly share code, notes, and snippets.

@brsc2909
Last active May 12, 2020 13:09
Show Gist options
  • Save brsc2909/461d793b42fc5dd6ea1a9f92b1441832 to your computer and use it in GitHub Desktop.
Save brsc2909/461d793b42fc5dd6ea1a9f92b1441832 to your computer and use it in GitHub Desktop.
Script to automatically Archive emails in all mailboxes, Does not require doveadm which is useful as often shared hosting does not have this installed
#!/bin/bash
##############################################################
# Author: Brendan Scullion
# Date: 11-May-2020
# Description:
# Run on a weekly or daily basis from crontab. In this example i am
# archiving all emails in every mailbox older that 1.5 Years. emails are moved to
# to the archive folder grouped by month and keep the original folder structure.
##############################################################
MAILROOT=/home/user/mail/domain.example.com
/bin/ls -d $MAILROOT/* | while read USER_MAIL_ROOT; do
find $USER_MAIL_ROOT -mtime +545 -type f -name "*${HOSTNAME}*" -print | grep -v $USER_MAIL_ROOT/.Archive | while IFS=$\n read -r email; do
T=$(/bin/ls -l --time-style="+%s" "$email"| sed -e "s/ / /g" | cut -d' ' -f6);
EMAIL_FILE=$(echo ${email##*/};);
REL_DIR=$(echo $email | sed -e "s^${EMAIL_FILE}^^g" | sed -e "s^${USER_MAIL_ROOT}/^^g");
if [ $email == $USER_MAIL_ROOT/cur/$EMAIL_FILE ]; then
ARCH_DIR=$(date --date="@$T" "+${USER_MAIL_ROOT}/.Archive.%Y.%m/${REL_DIR}");
if [ ! -d $ARCH_DIR ]; then
mkdir -p $ARCH_DIR;
fi
mv $email $ARCH_DIR$EMAIL_FILE;
else
ARCH_DIR=$(date --date="@$T" "+${USER_MAIL_ROOT}/.Archive.%Y.%m${REL_DIR}");
if [ ! -d $ARCH_DIR ]; then
mkdir -p $ARCH_DIR;
fi
mv $email $ARCH_DIR$EMAIL_FILE;
fi
done;
done;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment