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.

echo "[]:587" > /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/ for authentication options.

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

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

[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.]

4 thoughts to “Sendmail via GMail on Ubuntu Server”

    1. If you are authorizing with Google’s email servers, you cannot use TLS authentication instead of password. That said, password is transmitted over TLS.

    1. I must confess I didn’t. It looks as an easy enough to use from the command line but it doesn’t look as if PHP uses it by default (other than spawning a shell).

Leave a Reply

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