Email is hard.

Sending an email from a web application is a tricky prospect, as sending emails directly from your mail server is a good way to get the email sent to spam and your server blacklisted.

Therefore, it’s common these days to send your email through a third party service. These services can also offer value added functionality such as delivery reports, open and click tracking. All good stuff.

I recently had to wire this up for a client of mine, who was having problems sending emails from their application. So, the most expedient thing to do was hook them up with mailgun.

The common (and indeed recommended) method of interacting with mailgun, and other such delivery services, is through a web API. This is especially true in cloud environment, where you may have numerous servers that spool up and down based on demand.

However, my client was running their app on a traditional rack server, and they were not wanting to go the infrastructure as a service route right now. So, again, for expediency, I figured the simplest thing to do was to set up the machine to send all email through the mailgun servers.

This is called a smarthost, and is pretty easy to do (although does require some configuration).

Set up your mailgun domains

The first step is to set up your mailgun domain, and configure your DNS settings.

I’ll leave this as an exercise for the reader, and it is covered in some detail in mailgun’s documentation.

I will however mention that you should make sure you check your existing DNS records, and don’t pick a mailgun domain that clashes. I made this mistake, and got a bunch of 554 The domain is unverified and requires DNS configuration. errors in my logs, despite mailgun reporting everything was ok.

Recreating a fresh mailgun domain, and re-entering the DNS config resolved this.

Install and configure Postfix

apt-get install postfix

I opted to use postfix here, because it’s configuration is slightly easier than exim’s.

On debian, the installer will ask you to choose what kind of configuration you want. Select “smarthost” and enter smtp.mailgun.org as the server.

You’re now going to want to configure the upstream username and password, so that postfix will use your mailgun account information.

Edit you /etc/postfix/main.cf file and add the following:

Now edit /etc/postfix/password and enter your postfix username and password in the following format:

Once you’ve done that, build a hashed database file:

postmap /etc/postfix/password

Then reload your configuration:

postfix check; postfix reload

Now, any emails sent from your server (and by your web application) will automatically be sent through your mailgun server. Enjoy!

tail -f /var/log/mail.log

To see it in action (and to debug any problems).

Leave a Reply