Configure Postfix to send email through Gmail

When setting up a local development environment, sometimes you want to actually send real email. If you’re using WordPress, you can install a plugin to run your mail through an SMTP server. But if you’re running anything through the command line or you want to use the built-in PHP mail() function for any reason, then it’s really nice to be able to actually send mail.

Here’s a quick tutorial on how to set up Postfix to send email through your Gmail or G Suite account. I wouldn’t suggest sending a bunch of mail like this, but for the occasional needs that arise where you need to send out a few emails while working on a project, this is great.

Install the packages you need:

sudo apt install postfix mailutils libsasl2-2 ca-certificates libsasl2-modules

Open /etc/postfix/ and add the following lines

Provide your Gmail credentials in this file:
vi /etc/postfix/sasl_passwd

If you’re using G Suite, then you should use

Fix permissions 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 by running this command:
cat /etc/ssl/certs/GeoTrust_Primary_Certification_Authority.pem | sudo tee -a /etc/postfix/cacert.pem

Restart postfix so all the updates get loaded:
sudo service postfix restart

Test To See If It Worked

Run this command and see if you can send mail
echo "Test Message" | mail -s "Test From Postfix"

NOTE: should be a real email address. This is where the test message will be sent.

You can check this in two ways.
First: Check the sent folder in your Gmail account to see if the email was sent
Second: Check and see if the email is in your inbox

If Things Go Wrong

If the message did not send, check /var/log/mail.err and /var/log/mail.log for clues. You may need to tweak some of the settings in your /etc/postfix/ file.

For example, I had to tweak a couple things:

  • setgid_group = postdrop
  • mailq_path = /usr/bin/maiq
  • newaliases_path = /usr/bin/newaliases
  • sendmail_path = /usr/sbin/sendmail
  • comment out a few things like:
    • #html_directory
    • #manpage_directory
    • #sample_directory
    • #readme_directory

If you don’t know the path for a certain program, like mailq for example, you can type which mailq to get the path. The paths I listed above are for Ubuntu 17.10. Your paths may be different. Again, which will be your friend.

Leave a Reply

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