Own Your WordPress Email with Mandrill

It's the beginning of a new year, and Mandrill's modest growth continues!

To keep things rolling, we'd like to start talking about some nifty integrations out there that will help you leverage the tools Mandrill puts at your disposal. There are a number of good integrations already in the wild, including ones for Joomla! and Drupal.

But for today's safari, we're stalking the two ton elephant in the CMS room: WordPress.

One of the things WordPress does "for free" is send email. You've noticed this happening -- you get notified via email when someone leaves a comment or a new user registers, for instance -- but you may never have thought about customizing that process. We're here to tell you why you should!

Introducing wpMandrill

You've got WordPress running somewhere. I hesitate to call it a "blog", because WordPress has become a hulking behemoth of a content management system, and odds are you're already doing much more with it than just writing witty posts about latte art and dramatic rants about the evils of mainstream music. But one thing we're betting you're not doing is tracking the emails WordPress sends on your behalf. Naturally, that's where we come in.

For Mandrill, as with all good WordPress integrations, there's a plugin for that. It's called wpMandrill, and it's written and maintained by one of MailChimp's own developers using nothing but the public Mandrill API. How cool is that?

wpMandrill brings the advanced Mandrill transactional email tools to your WordPress emails. You get:

  • easy install: search for and install with a click from within WordPress
  • great delivery: don't trust your emails to chance!
  • reporting: know what works and find issues early
  • flexibility and customization

Over on the MailChimp blog, we've written a post about how to install and set up the plugin, as well as explaining more of the basics and why you might want to do this. Go check it out to get started, then head back over here to learn the more advanced techniques!

Again, go read this post now; going forward we'll assume you've got it installed and Mandrill is now sending your WordPress emails.

Easy Email Audits

You've got users, customers, and collaborators. Email glues your world together, from notifying moderators that there is moderation afoot, to sending your customers their receipts after all those purchases. Yes, email is the great back-channel that we barely think about, yet it keeps the trains running on time...

Except when it doesn't.

Jimmy bought your Super High Priced Widget last week, but he's writing you now to say, "Hey mate, where's my receipt? I never got one in my inbox..." What do you do?

Before Mandrill, it's hard to say what you would need to do. You would want to poke around in your WordPress logs... but where are they? Does your host even give you access to them? Once you find them, what do you search for? Can you do anything about what you find?

You might be successful getting through all of this, but why bother? When you use Mandrill to deliver your email, all of this rigmarole disappears and is replaced with a lovely search interface. Just type the user's email in the box and we'll tell you exactly what did (or did not!) get sent to them over the past month (or 3 months if there were, in fact, issues.)

We haven't exposed the full search interface into the wpMandrill dashboards yet, so you'll need to log into your Mandrill account proper to do this. But, as the advanced user that you are, you're going to want to spend some time on the Mandrill side of things, anyway. So go ahead and get comfortable with our interface, you'll be glad you did.

We've written some advanced articles about search in the past, so be sure to check out The Hidden Power of Search and Email as a Service as a Service.

Reports: What's Working... and What's Not

Being sure that your emails are getting to their destinations is a great first step, but we can do better: we can tell you if they're being opened and what links are getting clicked!

wpMandrill integrates charts and stats for you to dig deep from within the WordPress interface, as well as a dashboard widget for quick, "at a glance" checkups on how things are doing. Now, when you have an email problem, you'll know it immediately. It will smack you in the face (figuratively) the next time you log into WordPress to work.

Even better, reports allow you to be proactive with your emails. If you'd like to try something new, maybe a new subject line, some new body copy, or even an entirely new email for something you weren't previously sending, you'll want to watch your reports to see how they change.

If they go up, congratulations! Your changes are for the better, and your bottom line will surely grow as a result. But if they tank... Quick! Roll it back! You can always try another change or reel in the scope of your tweaks and try again.

Automatic Tagging

Tagging is a simple feature that opens up a lot of power. With Mandrill, you can tag your emails in order to organize and report on them later. You don't tag each individual email with a unique tag, but rather each type of email. Imagine tags like "welcome", "confirmation", "receipt", or "thank_you".

wpMandrill features automatic tagging for the emails WordPress sends. It detects which process is sending the email and adds a matching tag for you. For instance, the "wp_wp_new_user_notification" tag indicates that the "wp_new_user_notification" WordPress function triggered the send. (wpMandrill itself prepends that extra "wp_" to the tag to differentiate itself from other, non-automatic tags you may decide to use.)

At the end of the day, you'll be surprised at how much you can learn about your site just by sorting the email it sends. How many "new user" emails do you send relative to "new comment" emails? How many users are opening their receipts? Do your moderators actually click links in the comment moderation emails?

Multiple WordPress Installs

Does your business span multiple WordPress installs? Perhaps you're using WordPress Multisite to manage multiple assets under one roof?

No problem, you can install wpMandrill on every WordPress install you control. The settings can be configured independently of each other, which is very important when ensuring your users are getting the right messaging. You wouldn't want a user of your baseball site to get an email with your basketball template!

We also suggest you generate a new API key for each install. This limits your exposure if you ever need to change a key for some security-related reason. You don't want to have to go and change the key on every site you control!

One last note about multiple sites: it may be a good idea to make a new Mandrill account for some of your properties. It's a great deal more work due to juggling different login credentials and remembering what goes where, and you'll also lose the ability to compare stats between sites easily (which could be quite powerful!)

But, if your sites are different enough, it may be better to make separate accounts. Some possible scenarios where this may come into play:

  • one site has drastically more traffic than the rest
  • the sites are completely different businesses
  • you're a consultant or hosting provider: your clients need their own accounts

Common sense, yeah?

Advanced Customization with WordPress Filters

"That's cool", I hear you say, "but I have my blog, my store, and my forums all on one site! Do I still want to use Mandrill?"

Absolutely! Power users have that much more reason to use Mandrill. The auto-tagging functionality will mostly sort your email out for you in the reports, so you'll get heaps of value just by activating the plugin.

But you want to do more. You want to do custom things depending on the type of email. Perhaps something like:

  • attach custom tags (or even metadata)
  • change templates by email type
  • override the Reply-To address to go to support in some instances
  • perform custom logging

I'm going to talk about why and how to do this, but be warned: you're digging into the code now, and you'll be writing some code yourself in order to achieve these feats. Of course we can't guarantee things will go smoothly when your own code is involved, but we'll still happily support you!

Note on debugging: if in the course of your hacking you have an issue during sending, wpMandrill will fail over to the normal sending style. This is a feature to keep your service from being interrupted entirely, which would be bad. This can be confusing, though, as you'll still receive an email but it won't be the one you expected. Check the headers on your emails to ensure they are being delivered by mailXX.usX.mandrillapp.com and not your normal web host before pulling your last hair out!

One Filter, Infinite Possibilities

wpMandrill calls a filter, "mandrill_payload", just before it sends. This is your opportunity to intercept the email payload and modify it to your heart's content (within reason.)

Registering a filter handler (I put mine in my theme's "functions.php" file) looks like this:

add_filter('mandrill_payload', 'customFilterName');

In that example, you'd just need your own 'customerFilterName' function to receive the payload. Here's an example that does nothing:

function customFilterName($message)
    return $message;

The trick is that you want to modify that $message parameter before you return it. To understand what is actually in the thing, you'll want to glance at our API documentation for the 'send' call. This $message parameter is going to be sent as the "message" parameter to that API call, and it is already populated with the appropriate data from your settings.

For instance,


...will be set to something like "[yourwebsite.com] Your username and password" if the email is being sent to a new user who has just signed up.

If you changed the subject like this:

$message['subject'] = "ZOMG Welcome to Mah Blawg!";

...then that's what the subject would come out as. Not that we recommend that particular subject line.

Also, you don't want to just blindly overwrite the subject like that, because that would take effect on all of your emails, not just the welcome emails you were targeting. Instead, you'll want to identify what kind of email is being sent, then selectively modify things as desired.

The best way to branch on the different kinds of emails is to examine the tags. Remember, wpMandrill has already auto-tagged this message based on what triggered the original send, and it has stored those tags in $message['tags']['automatic'].

Once we've had Mandrill running for a bit we can see what tags there are in the Activity section of the web interface (see the image above in the "Automatic Tagging" section.) Looking at mine, I see the one I care about is "wp_wp_new_user_notification". Let's swap the subject line out in a more controlled fashion:

function filterWelcomeSubject($message)
    if(in_array('wp_wp_new_user_notification', $message['tags']['automatic']))
        $message['subject'] = "Welcome to Example Dot Com! Your credentials within...";

    return $message;

add_filter('mandrill_payload', 'filterWelcomeSubject');

And voila, you've got a custom subject line to welcome new users! You can see we simply checked for the presence of a certain tag in the automatic tags, and overwrote the subject line in only those instances.

Look again at the other options available for the messages/send API call, and experiment with different settings to suit your needs.

Overriding in Templates

Templates are a special case. If you've specified a general template in the wpMandrill settings page then your $message variable will have an additional array key: "template". This variable contains the information about which template will be used, and you can extend and modify these values as well.

If you specified a template named "main_template" in your settings, then you'll see it listed in the $message like this:

$message['template']['name']; // this will be "main_template"

...so changing out the template to use is as easy as setting it here:

$message['template']['name'] = 'ecommerce_template';

...just make sure you actually have a template in Mandrill by that name!

Tying all of this together, here's an example demonstrating template swapping based on the plugin that originated the email. If we were using bbPress forums and the Cart66 Lite eCommerce platform, we could define the following filter to change the templates for each:


function changeTemplate($message)
    // convenience variable
    $autoTags = $message['tags']['automatic'];

    // Is it a Cart66 email?
    if(in_array('wp_Cart66Common::mail', $autoTags))
        $message['template']['name'] = 'ecommerce_template';

    // Is it a bbPress email?
    elseif(strpos(implode(',', $autoTags),'wp_bbp_') !== false)
        $message['template']['name'] = 'forums_template';

    // Use the default template
    // Note: we could have specified a general template
    // in the settings and skipped this final 'else'
        $message['template']['name'] = 'blog_template';

    return $message;

// Don't forget to register the filter!
add_filter('mandrill_payload', 'changeTemplate');


Pretty straightforward, we hope!

Filling In Dynamic Templates

Ok, last trick! Let's look at how to fill in content in multiple dynamic regions of a template.

First of all, it's important to note that when you use templates, wpMandrill invokes a different Mandrill API call, namely messages/send-template. Have a look at it to see how it differs from the normal messages/send call.

Now I'm going to assume you've made a template with multiple dynamic regions as described in our knowledge base, and that you've named your regions 'user_name', 'main', and 'last_purchase'.

In order to fill in the dynamic regions, you'd do something like this:

$message['template']['content'][] = array(
    'name' => 'user_name',
    'content' => 'Freddie von Chimpenheimer IV'

$message['template']['content'][] = array(
    'name' => 'last_purchase',
    'content' => '3 Million Bananas'

...basically appending extra name-content pairs for each region you wish to fill in. The name must match the name of a an editable region, and the content is what will be filled in at that region.

You'll notice I didn't touch the 'main' region. That's because it is already filled in with the email body content ('main' is the default region). You could override it if you wanted, but normally you'll just leave it be.

However, if you don't set a general template in the wpMandrill settings, the main region won't be set up by default. Here's how you can set a template from scratch, if needed:

// Detect when no template was set
if(!isset($message['template'])) {
    // Create the template parameter
    $message['template'] = array();

    // Set a template
    $message['template']['name'] = 'my_template';

    // Fill in the main region with the normal content
    $message['template']['content'][] = array(
        'name' => 'main',
        'content' => $message['html']

    // Remove the normal content from its non-template location

wpMandrill will understand that you've added a template, and route the request through the appropriate API endpoint.

Knowledge is Power

Thanks for sticking with us on this long journey! We went through a lot, but this has just been a taste of what you can do. We've taken a wide approach to try and give a taste of what is possible, now it's up to you to dig in and go deep on your particular needs.

It'll take some work, but once you internalize the power Mandrill exposes, your WordPress strategy may change forever. (You have a WordPress strategy, right?) Knowing what is going on with your email is the first step to making valuable changes to how, why, and when you trigger an email.

For many people, email is a great untapped resource, a low-hanging fruit that they simply don't have the tools or knowledge to analyze and address. Once those tools are in place (now the easy part, thanks to wpMandrill), the next step is owning your communications channel and customizing the messages you send to your collaborators: this is where you want to be!

With simple integrations, we're bringing these "email power tools" to your world, whatever it may be. So tell us, where else should Mandrill go? What other platforms or CMSes would you like to see Mandrill integrate with?