Using Gmail or Google Apps for sendmail and postfix on Ubuntu

Woman holding a mailbox

Lots of people have been asking us to update our previous guide on using Gmail and Google Apps under CentOS for Ubuntu. Wait no longer!

As a background, many ISPs block sending email over port 25 which means that you won’t be able to send mail from your Ubuntu server through simple commands like mailx or logwatch. Additionally, you may just want to send your emails via your Gmail/Google Apps account to avoid the emails being flagged as spam. A good way to get around this limitation is to set up a relay through a Gmail account.

The following instructions were tested on Ubuntu 16.04 and 18.04.

REQUIRED PACKAGES

You will need the libsasl2 modules and postfix installed, so install them if you haven’t already with this command:

Choose Internet Site when asked in the postfix configuration screen.

Postfix configuration screen

Enter your system’s fully qualified domain name:

Postfix enter the FQDN

GMAIL APP PASSWORD

If you have Two Factor Authentication enabled for GMail, you’ll need to create an app password that you can use for this server to send emails. You can find out how to do that at this link, and then come back here.

CREATE THE PASSWORD FILES

Create the file /etc/postfix/sasl_passwd with sudo in your favorite text editor, and fill in the following on one line:

Next, we’ll need to hash that file so that it’s more secure. First, make sure that /etc/postfix is owned by the postfix user, or you’ll get an error message stating “postmap: fatal: open database /etc/postfix/sasl_passwd.db: Permission denied”:

SECURE THE PASSWORD FILES

The files /etc/postfix/sasl_passwd and /etc/postfix/sasl_passwd.db will both still exist on your computer even after hashing. Please make sure that both are owned by user and group root. Set the file permissions to 600 for both files:

EDIT THE POSTFIX CONFIG

With sudo, edit the /etc/postfix/main.cf configuration file:

Find the relayhost line and change it to the following:

Next, add the following lines at the end:

Restart postfix with this command:

SENDING MAIL

If you don’t have the mail command installed already, install it with this command:

Next, use this command to test things out:

You can watch the syslog output to see if there are any errors in your setup – sometimes you’ll see Gmail errors here if something is not configured correctly.

OTHER NOTES:

Set postfix to only use ipv4 to fix ipv6 routing issues with gmail:
http://linuxmoz.com/google-mail-ipv6-network-is-unreachable-postfix-ipv4-only-fix/

Be the first to comment

Leave a Reply

Your email address will not be published.


*