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
/etc/postfix/main.cf and add the following lines
relayhost = [smtp.gmail.com]:587 smtp_sasl_auth_enable = yes smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd smtp_sasl_security_options = noanonymous smtp_tls_CAfile = /etc/postfix/cacert.pem smtp_use_tls = yes
Provide your Gmail credentials in this file:
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" email@example.com
firstname.lastname@example.org 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
email@example.com and see if the email is in your inbox
If Things Go Wrong
If the message did not send, check
/var/log/mail.log for clues. You may need to tweak some of the settings in your
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:
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.