depicus

changing the digital world one bit at a time...

Blants (noun) the rants of a blogger

Using Google SMTP with Postfix on Ubuntu/Debian

December 22, 2014 by The Man

I run a few servers at home for various things including a little Raspberry Pi running Debian which emails me alerts when certain things happen. I send these to an Outlook.com account or an Office365 account but being a home IP I often get blocked

“(host mx2.hotmail.com[65.55.33.119] said: 550 OU-002 (COL004-MC5F2) Unfortunately, messages from xxx.xxx.xxx.xxx weren’t sent. Please contact your Internet service provider since part of their network is on our block list.”

So the simple solution is to add a relay host to Postfix.

First let’s open up the Postfix config file

sudo nano /etc/postfix/main.cf

and add the following text…

relayhost = [smtp.gmail.com]:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_tls_CAfile = /etc/postfix/cacert.pem
smtp_use_tls = yes

Save the file, next we are going to create a password file to store our Gmail account details which keeps them away from the main Postfix config file. So type…

sudo nano /etc/postfix/sasl_passwd

and we want to add the following line

[smtp.gmail.com]:587 yourusernamehere@gmail.com:password

Now one of the GREAT reasons to use two factor authentication is that Gmail won’t allow you to use your password in the line above. If you don’t use two factor authentication WHY !!! but you can then just put in your password but otherwise go to Googles App Setup page and create an app specific password. This has the added bonus that you can revoke should your machine be compromised and you cannot get in.

Now we have set up the details lets go ahead and secure that file

sudo chmod 400 /etc/postfix/sasl_passwd

and tell postmap about our password file

sudo postmap /etc/postfix/sasl_passwd

and let’s finally copy a certificate

cat /etc/ssl/certs/Thawte_Premium_Server_CA.pem | sudo tee -a /etc/postfix/cacert.pem

then restart Postfix

sudo service postfix restart

Now we need to test we got everything working so lets install something so we can send mails from the command line.

sudo apt-get install mailutils

Once installed you should be able to now send a test email to make sure it worked.

echo "Can we get an email through Gmail" | mail -s "When we get blocked" bob@example.com

If you don’t get the email take a look at /var/log/mail.log for errors.