Redirect all sent emails to one address.

On a development laptop, I wanted all email generated by a website running locally to get redirected to my own email address. Postfix is automatically loaded on Mac OS X (it doesn’t officially run until invoked by a program, so you won’t see it in the Activity Monitor). It took a lot of Googling to sort this out, and it’s not very hard, so here it is. There are two parts. One, is to catch all emails and redirect them. The second part is to configure postfix to use an SMTP relay for actually sending the messages. I use http://sendgrid.com/, and the relay instructions below are tuned speficially for them. Your config could differ if you use a different SMTP provider, but at the very least you can follow the first part of these instructions to capture emails to prevent accidental spam from your local machine.

Capture all emails to prevent accidental spam

edit /etc/postfix/main.cf and add

canonical_maps = regexp:/etc/postfix/canonical-redirect`

create /etc/postfix/canonical-redirect and enter the address you want all emails sent to.

/^.*$/ your_email@example.com

or, if you’re not setting up SMTP relay below, change your_email@example.com to your username on your Mac, which will deliver mail to your local account (I’m not sure how you’d read it though, so that’s why I also set up the SMTP relay business).

From the command line, execute sudo postmap /etc/postfix/canonical-redirect . This command will create the file /etc/postfix/canonical-redirect.db which postfix will find automatically. Just in case, also execute sudo postfix reload although you’ll probably get an error message that postfix isn’t running (which is OK, but if it was, this would be needed to pick up the changes to main.cf).

Setup SMTP relay with Sendgrid

Sendgrid documents this here. The following is what works for me. Add the following to /etc/postfix/main.cf

smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = static:your_sendgrid_username:your_sendgrid_password
smtp_sasl_security_options = noanonymous
smtp_tls_security_level = may
smtp_use_tls = yes
header_size_limit = 4096000
relayhost = smtp.sendgrid.net:587

Try sudo postfix reload from the terminal just in case. You can test things with the following from the command line echo "testing the message body" | mail -s "test the subject" john@example.com and you can check the log file to see what postfix thinks about it cat /var/log/mail.log in case you didn’t receive it in your inbox.

Enjoy!