Sendmail via GMail on Ubuntu Server

I finally decided to migrate my Wordpress onto Ubuntu 20.04 only to discover e-mail I configured via Smtpmail stopped working. That meant my WordPress and various PHP and command line tools couldn’t use Google’s e-mail relay to deliver e-mails to my Inbox. It was time to setup my server to use Google’s SMTP again. And this time I decided to go with postfix.

Installing postfix usually involves a GUI asking a few questions. However, you can use debconf-set-selections to preload the answers. Make sure to be the root used (sudo su -).

debconf-set-selections <<< "postfix postfix/main_mailer_type string 'Internet Site'"
debconf-set-selections <<< "postfix postfix/mailname string ''"
apt-get install --assume-yes postfix libsasl2-modules

Once installed, we need to provide credentials in /etc/postfix/sasl/sasl_passwd.

unset HISTFILE
echo "[smtp.gmail.com]:587 ^^relay@gmail.com^^:^^password^^" > /etc/postfix/sasl/sasl_passwd
postmap /etc/postfix/sasl/sasl_passwd
chmod 0600 /etc/postfix/sasl/sasl_passwd /etc/postfix/sasl/sasl_passwd.db

Finally we need to update /etc/postfix/main.cf for authentication options.

sed -i 's/relayhost = /relayhost = [smtp.gmail.com]:587/' /etc/postfix/main.cf
cat <<EOF >> /etc/postfix/main.cf
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl/sasl_passwd
smtp_sasl_security_options = noanonymous
EOF

And that’s pretty much it. The only remaining thing is to restart postfix:

systemctl restart postfix

To test if it works, just use sendmail.

echo "Subject: Test via sendmail" | sendmail -v ^^youremail@example.com^^

[2022-06-16: As of 2022-06-01, it’s not possible to use your Google email and password directly. However, you can still follow this guide and use App Password instead.]