PHP, sendmail And Mandrill

One of the first things that has to happen when I start working on a new project, is to ensure that mail sending is handled by a third-party service. Preferably something like Mandrill or Mailgun. I have no desire to maintain mailservers, SMTP stuff and what not.

Today I had a challenge, when moving a lot of old code to a new Linode server. Most of the code was sending e-mails through a third party package, and was already configured to send through Mandrill. However, some of the code was still using mail(), so I had to somehow configure sendmail to run on the server, in order to not break the app. Just the name, sendmail, makes my palms sweaty.

In the end, I came up with a really simple solution that can easily run until that code has been refactored.

Step 1: Install sendmail

First of all, we need a sendmail binary. I’m writing ‘a’ and not ‘the’, since multiple Ubuntu packages can provide a sendmail binary. Take a look at this:

$ sendmail
The program 'sendmail' can be found in the following packages:
 * exim4-daemon-heavy
 * exim4-daemon-light
 * lsb-invalid-mta
 * postfix
 * citadel-mta
 * courier-mta
 * dma
 * esmtp-run
 * lsb-invalid-mta
 * masqmail
 * msmtp-mta
 * nullmailer
 * qmail-run
 * sendmail-bin
 * ssmtp
 * xmail
Ask your administrator to install one of them

The ‘trick’ here is to use nullmailer, which is a small program that can only forward e-mails to another MTA (message transfer agent). At least as far as I have understood. Anyways, installing nullmailer on Ubuntu is pretty pain-free:

$ sudo apt-get install nullmailer

Step 2: Configure nullmailer

While installing, you will be prompted for a few options. First thing, you need to provide the fully-qualified host name for the server. You will know better than me what this is! Next thing, nullmailer will allow you to specify a ‘smarthost’ to connect to. Here is the one I used for Mandrill:

smtp.mandrillapp.com smtp --user=[username] --pass=[password] --port=587

If at some point you want to edit this, you can do so in /etc/nullmailer/remotes.

Step 3: Test it out

To test it out, you can try to send a test e-mail from the server. First, create a text file with the e-mail:

# testmail.txt

Subject: Test mail from server

This is a test mail from sendmail.

Now, use sendmail to send the e-mail:

sendmail you@example.com < testmail.txt

You can check you mail queue to see if the message was sent:

$ mailq

And that’s it!