All too often I get asked questions about emails which I can't answer because I can't actually see the emails. While mail logging goes a long way, I'd really like to keep an archive of all mails sent via an SMTP server on that machine. Here's how to do that with Postfix. This was tested on Ubuntu 14.04, but should be applicable to other foonixes 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
Next, 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
Configure Postfix to always send a copy of any emails sent to the mailarchive user:
postconf -e always_bcc=mailarchive@localhost
Configure the mail storage for the mailacrhive user so it uses the Mailbox format. This makes it easier to delete old emails:
# echo "mailarchive: /var/archive/mail/" >> /etc/aliases
# newaliases
Finally, restart postfix
/etc/init.d/postfix restart
Now to test it send an email through the SMTP server. I'll do a manual SMTP session here:
telnet localhost 25
HELO localhost
MAIL FROM: fboender@localhost
RCPT TO: ferry.boender@example.com
DATA
Subject: Mail test
Here's some mail.
.
QUIT
We check the /var/archive/mail/new directory:
ls /var/archive/mail/cur/
1425653888.Vfc00I461477M767603.posttest4:2,
And there is our mail.
To easily view the mail in the archive, install mutt:
apt-get install mutt
mutt -f /var/archive/mail/
You should probably write a cronjob that regularly cleans out the old mail, otherwise your filesystem will fill up. The following cronjob will delete all mail older than 30 days
cat /etc/cron.daily/mailarchive_clean
#!/bin/sh
find /var/archive/mail/ -type f -mtime +30 -exec rm "{}" \;
chmod 755 /etc/cron.daily/mailarchive_clean
Edit: Changed postfix configuration addition to postconf -e