Postfixadmin. Removing old mailboxes.

Our organization mail server hosts several domains with more than 750 mailboxes. We use commercial antispam and antivirus software. License value is calculated from the number of mailboxes. Therefore it’s important to keep mailbox database actual and remove unused accounts.

Mail server setup is based upon postfix mail server daemon and Postfixadmin web-based administration interface which uses MySQL to store configuration data. I wrote simple shell script to find and delete mailboxes which were not used for more than 1 year:

#!/bin/sh

YEAR=31536000
MYSQL="/usr/bin/mysql -D postfix -u postfix -ppassword -e"
DOMAIN=your.domain

cd /var/spool/vmail/$DOMAIN
for i in *; do
    MDATE=`stat --format=%y $i/cur`
    MUTDATE=`stat --format=%Y $i/cur`
    CTIME=`date +%s`
    if [ `expr $CTIME - $MUTDATE` -ge $YEAR ]; then
        echo "Removing $i@$DOMAIN mailbox. Last pop3 delivery was on $MDATE"
        $MYSQL "DELETE FROM alias WHERE address = '$i@$DOMAIN'"
        $MYSQL "DELETE FROM alias WHERE goto = '$i@$DOMAIN'"
        $MYSQL "DELETE FROM mailbox WHERE username = '$i@$DOMAIN'"
        /bin/rm -rf $i
    fi
done

Date comparison is pain in bash scripting. Idea here was to use Unix time to avoid separate comparison of year, month and day. Thank stat can output time in different formats. YEAR is 1 year in seconds.

Each time user receives his mail from mail server letters are moved from new to cur dir. After mail has been received postfix deletes letters from cur. This script determine if user hasn’t been receiving mail for more than 1 year by checking modification time of cur dir of his mailbox. Script removes metadata from MySQL database and actual maildir of old box.

Using this script I found and removed more than 250 abandoned mailboxes.

Tags: , , , , , , , , , , , ,

One Response to “Postfixadmin. Removing old mailboxes.”

  1. Zoli Says:

    Thank you, this is very useful. If anyone want to use for a multi domain system, here is the modified script:

    #!/bin/sh

    YEAR=31536000

    MYSQL=”/usr/bin/mysql -D postfix -u root -pyourrootpassword -e”
    cd /var/spool/vmail

    for DOMAIN in *; do
    for i in “$DOMAIN”/*; do
    dom=`echo $i | cut -d’/’ -f1`
    user=`echo $i | cut -d’/’ -f2`
    MDATE=`stat –format=%y $i/cur`
    MUTDATE=`stat –format=%Y $i/cur`
    CTIME=`date +%s`
    if [ `expr $CTIME – $MUTDATE` -ge $YEAR ]; then
    echo “Removing $user@$dom mailbox. Last pop3 delivery was on $MDATE” >> /opt/deleted_users
    $MYSQL “DELETE FROM alias WHERE address = ‘$user@$dom'”
    $MYSQL “DELETE FROM alias WHERE goto = ‘$user@$dom'”
    $MYSQL “DELETE FROM mailbox WHERE username = ‘$user@$dom'”
    /bin/rm -rf $i
    fi
    done
    done

Leave a comment