Configuring Postfix to send mail through MailGun

This article is about how to configure your Linux server to send mail through the MailGun service.

First you need to make sure everything is fine with your account. For that you can use the curl utility and send a message through the API:

curl -s -user 'api:YOUR_API_KEY' \  
https://api.mailgun.net/v3/domain/messages \  
-F from='Excited User <mailgun@domain>' \  
-F to=YOU@domain> \  
-F subject='Test' \  
-F text='Mailgun check'

Make sure the packages we need are present in the system:

CentOS/RedHat:

yum install postfix cyrus-sasl-plain cyrus-sasl-md5

Ubuntu/Debian:

apt-get update apt-get install postfix libsasl2-modules

Next you need to edit the postfix config file:

vim /etc/postfix/main.cf

Add the following lines at the end:

smtp_sasl_auth_enable = yes
relayhost = smtp.mailgun.org            
smtp_sasl_security_options = noanonymous
smtp_sasl_password_maps=hash:/etc/postfix/sasl_passwd

Create the file with the login:

vim /etc/postfix/sasl_passwd

Put the following information into it:

smtp.mailgun.org [email protected]:password

Create the hash:

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

Restart postfix to apply the changes:

service postfix restart