Keep an Archive of E-Mails Going through a Postfix SMTP Server for 3 Hours

We often need to check the content of email going through our postfix SMTP server. In Bukalapak, sometimes I need to do that to check whether a particular user gets their email correctly. Truth be told, we can't actually see the email contents without getting the emails itself.

Here's how to do that with Postfix. This was tested on Ubuntu 14.04, but should be applicable to other Linux distribution without too much trouble. Run all this as the root user.

Add a user to the system so postfix can send BCC's of all emails to it
adduser --system --home /var/archive/mail/ --no-create-home --disabled-password mailarchive  
Create the Mailbox layout for the mail archive
mkdir -p /var/archive/mail/tmp  
mkdir -p /var/archive/mail/cur  
mkdir -p /var/archive/mail/new  
chown -R nobody:nogroup /var/archive  
Add this line on postfix configuration file main.cf
# save sent mail
always_bcc = mailarchive@localhost  
Configure the mail storage for the mail archive user so it uses the Mailbox format. This makes it easier to delete old emails
# echo "mailarchive: /var/archive/mail/" >> /etc/aliases
# newaliases
Restart postfix
service postfix restart  
Test Send Email through this mail server

You can use swaks to do this. If you haven't installed it. Simply install it using apt-get install swaks.

echo "This is the message body" | swaks --to lukman@bukalapak.com --from "test@noreply.bukalapak.com" --server <smtp-ip>:587 -tls  
Install Mutt to Easily View the Mail in the Archive
apt-get install mutt  
mutt -f /var/archive/mail/  

To search through the emails using mutt, you can check this link for the manuals.

Next, Create Script to Delete Mails Older than 3 Hours

This is a simple bash script that I create to automate mail deletion. Save it as /usr/bin/delete-mail.sh.

#!/bin/bash

THRESHOLD=$2  
MAIL_DIR=$1  
threshold_del=`date +%Y%m%d-%H --date="-$THRESHOLD hour"`

for mail in `ls --time-style='+%Y%m%d-%H' -lh $MAIL_DIR | grep -v total | awk '{print $6 " " $7}' | grep "$threshold_del" | awk '{print $2}'`;  
do  
  rm $MAIL_DIR/$mail
done  

Change its permission.

chmod +x /usr/bin/delete-mail.sh  

Add a cronjob on /etc/crontab.

# delete mail older than 2 hours
0 * * * *   root    /usr/bin/delete-mail.sh /var/archive/mail/new 2  
0 * * * *   root    /usr/bin/delete-mail.sh /var/archive/mail/cur 2  
Thats it.

Lukman

Radio astronomer pretending to be system engineer.

Bandung, Indonesia