メールの自動削除

アカウントを払い出しているユーザのうち、一部はメールを溜め込んでいたり、単にSPAMの温床になっていたりするものがあるので、メールは定期的に削除してしまえ、とか考えてみた。

/usr/local/bin/maildir-cleanup

#!/bin/sh

if [ $# -ne 2 -o ! -d "$1" -o "$2" -lt "1" ]; then
    echo ''
    echo "Usage: $0 <directory> <days>"
    echo ''
    echo '  Delete mail files older than specified days from the specified maildir'
    echo '  This program will delete <directory>/(new|cur|tmp)/*'
    echo ''
    exit 1
fi
/usr/bin/find $1/new -type f -ctime +$2 -print | xargs -r -n 1 -t rm -f
/usr/bin/find $1/cur -type f -ctime +$2 -print | xargs -r -n 1 -t rm -f
/usr/bin/find $1/tmp -type f -ctime +$2 -print | xargs -r -n 1 -t rm -f
exit 0

がっさり削除するわけだけど、これ以外にSPAMはもっと早く消したいとか思ってみて、
/usr/local/bin/maildir-spamcleanup

#!/bin/sh

if [ $# -ne 2 -o ! -d "$1" -o "$2" -lt "1" ]; then
    echo ''
    echo "Usage: $0 <directory> <days>"
    echo ''
    echo '  Delete mail files older than specified days from the specified maildir'
    echo '  This program will delete <directory>/(new|cur|tmp)/*'
    echo ''
    exit 1
fi
/usr/bin/find $1/new -type f -ctime +$2 -exec egrep -l "^X-Spam-Flag: YES$" {} \; | xargs -r -n 1 -t rm -f
/usr/bin/find $1/cur -type f -ctime +$2 -exec egrep -l "^X-Spam-Flag: YES$" {} \; | xargs -r -n 1 -t rm -f
/usr/bin/find $1/tmp -type f -ctime +$2 -exec egrep -l "^X-Spam-Flag: YES$" {} \; | xargs -r -n 1 -t rm -f
exit 0

で、これらをまとめるスクリプトまで作って、
/usr/local/bin/mail-cleanup

#!/bin/sh

if [ $# -ne 3 -o -z "$1" -o "$2" -lt "2" -o "$3" -lt "2" ]; then
    echo ''
    echo "Usage: $0 <user> <spamdays> <days>"
    echo ''
    echo "  Delete mail files older than specified days in the specified user's mailbox."
    echo '  This program will delete'
    echo '      ~<user>/Maildir/(new|cur|tmp)/*'
    echo '      ~<user>/Maildir/*/(new|cur|tmp)/*'
    echo ''
    exit 1
fi

spamdays=$2
days=$3
eval userhome=~$1
if [ -z "$userhome" -o ! -d "$userhome" ]; then
    echo "Error: '$1' has no home directory."
    exit 1
fi
/usr/local/bin/maildir-cleanup $userhome/Maildir $days
/usr/bin/find $userhome/Maildir -maxdepth 1 -type d ! -name cur ! -name new ! -name tmp \
        -exec /usr/local/bin/maildir-cleanup {} $days \;
/usr/local/bin/maildir-spamcleanup $userhome/Maildir $spamdays
/usr/bin/find $userhome/Maildir -maxdepth 1 -type d ! -name cur ! -name new ! -name tmp \
        -exec /usr/local/bin/maildir-spamcleanup {} $spamdays \;

evalでホームディレクトリを取得しているところは2chの「シェルスクリプト総合」スレにThanks。
あと、findで無理矢理メールフォルダと思わしきディレクトリを取得しているのは遣っ付け仕事だな。
で、

mail-cleanup hogeuser 5 90

とかやれば、hogeuserのメールボックスから、5日以上前のSPAMメールと、60日以上前の全てのメールを一括削除して、標準エラーに何を消したかを出力してくれる。
ということで、
/etc/cron.daily/mailbox-cleanup

#!/bin/sh
/usr/local/bin/mail-cleanup hogeuser 60 60
/usr/local/bin/mail-cleanup fugauser 5 999

とかしておけばハッピー。