TOPICS
Tutorials

Configure Postfix to Relay over SMTP+SASL

Here, we will set up a Postfix installation that relays e-mails via another mail server with authentication. This is useful for several purposes:

  • You already have a mail server, and want your web applications to send e-mail via local Postfix instead of directly connecting to your mail server from the application. This reduces latency in the application, and also makes delivery more reliable (Postfix will retry sending the message several times).
  • You want to relay e-mail over Gmail or another similar e-mail service.

Install Postfix

The first step is, of course, to install Postfix:

sudo apt-get install postfix

The installer will prompt you to select a template for the configuration file. If all e-mail is going to be relayed, select "Satellite"; then enter the SMTP server on the next prompt (e.g. "[smtp.gmail.com]:587").

Note: you need to put brackets around the hostname, like "[example.com]" or "[example.com]:587", since we want to authenticate with the mail server; if we simply used "example.com", then Postfix would look for an MX record and we might end up at an incoming mail server rather than the one that accepts authentication.

Configure Authentication

Now, we want Postfix to authenticate with the SMTP server. If you want to relay via your own mail server, an alternative would be to update your mynetworks setting on the target mail server to accept e-mail without authentication (i.e., authorize by IP address). Here, though, we'll use username/password authentication.

First, edit /etc/postfix/main.cf. You should already see this line if you selected satellite (if not, then you need to add or modify the line):

relayhost = [smtp.example.com]

Below it, add some additional options to enable authentication:

smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options =
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
smtp_use_tls = yes

Here, we are telling Postfix to both use SASL authentication, and also enable TLS for secure communication. We also provide two paths, one for trusted certificate authorities and one for the login credentials.

We now create the /etc/postfx/sasl_passwd file containing login credentials. Replace smtp.example.com with the hostname (without brackets) used in relay host, and also put your actual username and password:

smtp.example.com username:password

Update permissions on the file to make it readable only by root user, and create the hash database:

sudo chmod 600 /etc/postfix/sasl_passwd
sudo postmap /etc/postfix/sasl_passwd

Finally, reload Postfix and try sending an e-mail:

service postfix reload
echo 'test' | mail -s 'test' you@example.com