How to configure postfix to use Gmail SMTP on Ubuntu

If you do not have postfix installed before, postfix configuration wizard will ask you some questions. Just select your server as Internet Site and for FQDN use something like mail.example.com

Then open your postfix config file:

vim /etc/postfix/main.cf

and following lines to it:

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

You might have noticed that we haven’t specified our Gmail username and password in above lines. They will go into a different file. Open/Create

vim /etc/postfix/sasl_passwd

If you want to use your Google App’s domain, replace @gmail.com with your @domain.com

Fix permission and update postfix config to use sasl_passwd file:

sudo chmod 400 /etc/postfix/sasl_passwd
sudo postmap /etc/postfix/sasl_passwd

Next, validate certificates to avoid running into error. Just run following command:

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

Note: If you run into issues with above command, try changing certificate name to thawte_Primary_Root_CA.pem in above command. Thanks Alexander Bakker for the note.

Finally, reload postfix config for changes to take effect:

sudo /etc/init.d/postfix reload

or

sudo systemctl restart postfix

Testing

Check if mails are sent via Gmail SMTP server

If you have configured everything correctly, following command should generate a test mail from your server to your mailbox.

echo "Test mail from postfix" | mail -s "Test Postfix" [email protected]

To further verify, if mail sent from above command is actually sent via Gmail’s SMTP server, you can log into Gmail account [email protected] with PASSWORD and check “Sent Mail” folder in that Gmail account. By default, Gmail always keeps a copy of mail being sent through its web-interface as well as SMTP server. This logging is one strong reason that we often use Gmail when mail delivery is critical.

Once configured, all emails from your server will be sent via Gmail. This method will be useful if you have many sites on your server and want them all to send emails via Gmail’s SMTP server.

If you encounter an error message Error: “SASL authentication failed; server smtp.gmail.com” , you need to unlock the captcha by visiting this page:

https://www.google.com/accounts/DisplayUnlockCaptcha

You can run test again after unlocking captcha.

Source: https://rtcamp.com/tutorials/linux/ubuntu-postfix-gmail-smtp/

Leave a Comment

Your email address will not be published. Required fields are marked *