Relaying Email Through Google

Let's say you have an Ubuntu server and want to send email from the server for notification purposes AND you want the email to go to your inbox and not end up in the spam folder. Here's what you need to do.

First, install mailutils and libsasl2-modules. The libsasl2-modules package is necessary for authentication to Google's mail servers.

apt-get install mailutils libsasl2-modules

Now, we'll need a text file containing the user login for the Google account which we'll be using to access the Google relays. If it doesn't already exist, create a folder called 'sasl' in the /etc/postfix directory.

mkdir /etc/postfix/sasl

Then, within the sasl folder, create a file called 'sasl_passwd' or whatever you want to call it.

nano /etc/postfix/sasl/sasl_passwd

Within the sasl_passwd file, enter the following line.

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

We need to create a hash db file for postfix.

postmap /etc/postfix/sasl/sasl_passwd

Next, edit postfix's main.cf file and add the following lines:

# Enable SASL authentication
smtp_sasl_auth_enable = yes
# Disallow methods that allow anonymous authentication
smtp_sasl_security_options = noanonymous
# Location of sasl_passwd
smtp_sasl_password_maps = hash:/etc/postfix/sasl/sasl_passwd
# Enable STARTTLS encryption
smtp_tls_security_level = encrypt
# Location of CA certificates
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

Edit the following line in main.cf to look like this:

relayhost = [smtp.gmail.com]:587

Finally, restart postfix.

systemctl restart postfix

In some cases, Google won't relay. Try allowing Less Secure Apps to fix this.