Configuring Postfix to Send E-mails Through an External SMTP Server

There are certain cases where you want to set up Postfix to send emails through an external server. One such case is when you are developing a website on your laptop, and want to test a contact form before uploading to your production server. Sending e-mails from a dynamic IP is generally a bad idea, since most email providers will automatically flag the message as spam. That leaves us with the option of forwarding the message to a "real" SMTP server.

This tutorial will show you how to set up Postfix to relay emails through an external SMTP server. If you don't have your own SMTP server, you can alternatively use a free SMTP server, such as Gmail. The steps below have been successfully tested on Ubuntu 14.04 and 15.04.

  1. Start by installing Postfix:

    $ sudo apt-get install postfix mailutils
    
  2. Assuming that your SMTP server listens on SMTP.DOMAIN.TLD:587, replace the contents of /etc/postfix/main.cf with:

    inet_interfaces = loopback-only
    relayhost = [SMTP.DOMAIN.TLD]:587
    smtp_sasl_auth_enable = yes
    smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
    smtp_sasl_security_options = noanonymous
    smtp_use_tls = yes
    smtpd_client_restrictions =
     permit_mynetworks
     reject
    
  3. Edit /etc/postfix/sasl_passwd, and insert your login USERNAME and PASSWORD:

    [SMTP.DOMAIN.TLD]:587 USERNAME:PASSWORD
    
  4. Change the file permissions, so that only root has access to it:

    $ sudo chown root:root /etc/postfix/sasl_passwd && sudo chmod 400 /etc/postfix/sasl_passwd
    
  5. Convert the text file to a database file:

    $ sudo postmap /etc/postfix/sasl_passwd
    
  6. Finally, restart Postfix for changes to take effect:

    $ sudo service postfix restart
    

That's it! In case of troubleshooting, don't forget to check the Postfix log file at /var/log/mail.log.