MandrillX Class Tutorial

I could tell you how many hours it takes to develop a MODX extra Transport Package complete with a build script, properties, multiple MODX elements, internationalized strings, error checks, and then fully test it, but you wouldn't believe me. If you use this extra and like it, please consider donating. The suggested donation for this extra is $10.00, but any amount you want to give is fine (really). For a one-time donation of $50.00 you can use all of my non-commercial extras with a clear conscience.


PayPal

MandrillX is a class for sending email through Mandrill. Mandrill is an offshoot of MailChimp. It is geared for sending transactional emails, but you can send bulk emails with Mandrill as well. Mandrill allows you to send up to 12,000 emails per month for free. Beyond that, the prices are quite reasonable. At first, you may be limited to 250 emails per hour, but if you go over, the additional emails will be queued and sent later.

Getting a Mandrill Account and API Key

This is really easy. Go to Mandrill and click on the blue "Sign Up" button.

Follow the instructions. As soon as you've verified your account, log in at Mandrill. Hover over the little gear icon at the upper right and select the top option, "SMTP & API Credentials."

Click on the blue "New API Key" button. Once you have an API key, copy it to the clip board so you can enter it when installing MandrillX. If you've already installed MandrillX you can simply set the mandrill_api_key System Setting to your key. You can change the key at any time.

Before leaving the Mandrill web site, hover over the "Outbound" option on the top menu and select "Subaccounts." Create a subaccount called test (all lowercase). This is important because it is the default subaccount used by MandrillX. If the account doesn't exist, your test emails will fail. Once you're done testing, you can create a new subaccount (or several of them) and set the subaccount property in the $scriptProperties array to direct the emails to a given subaccount. At that point you may want to delete the test subaccount.

Installing MandrillX

Go to System | Package Management on the main menu in the MODX Manager and click on the "Download Extras" button. That will take you to the Revolution Repository (AKA Web Transport Facility). Put MandrillX in the search box and press Enter. Click on the "Download" button, and once the package is downloaded, click on the "Back to Package Manager" button. That should bring you back to your Package Management grid. Click on the "Install" button next to MandrillX in the grid. The MandrillX package should now be installed.

Usage

MandrillX wraps the Mandrill PHP class to make things a little simpler. Here is a minimal example that sends mail using MandrillX. It assumes that you have an account at Mandrill, and have set the mandrill_api_key system setting:

    require_once MODX_CORE_PATH . 'components/mandrillx/model/mandrillx/mandrillx.class.php';

    $msgContent = '<p> Hello {{+fullname}}, this message is for you.</p>';

    $scriptProperties['subject'] = 'Update from ' . $modx->getOption('site_name');
    $scriptProperties['from_name'] = 'Your Name';
    $scriptProperties['from_email'] = 'youremail@somewhere.com';
    $scriptProperties['subaccount'] = 'test';

    $apiKey = $this->modx->getOption('mandrill_api_key');
    $mx = new MandrillX($modx, $apiKey, $scriptProperties);
    $mx->init();

    $mx->setHTML($msgContent);

    $userFields = array(
    'name' => 'Some User',
    'email' => 'someuser@somewhere.com',
    'fullname' => "User full name",
    );
    $mx->addUser($userFields);

    $userFields = array(
    'name' => 'Some Other User',
    'email' => 'someotheruser@somewhere.com',
    'fullname' => "Other User full name",
    );
    $mx->addUser($userFields);

    /* Send the mail */

    $results = $mx->sendMessage();

Initialization

The three arguments to the MandrillX constructor are the $modx object, the Mandrill API key (as a string), and the $scriptProperties array. Only the first one is strictly necessary, though you may want to set the 'subject', 'from_email', and 'from_name' members of the $scriptProperties array. If you don't, the email subject defaults to 'Update from Bob's Guides', the from_email address defaults to the emailsender System Setting, and the from_name defaults to Bob's Guides.

If the API key is not sent, MandrillX will try to get it first from the $scriptProperties array, and then from the mandrill_api_key System Setting.

If you do want to set the fields in the $scriptProperties array, they must be set before instantiating the MandrillX object, because they are sent in the constructor.

Subaccounts

Each message or groups of messages you send can be assigned to a subaccount. With MandrillX, you specify the subaccount with the 'subaccount' member of the $scriptProperties array. The subaccount you specify *must exist at Mandrill* or the send will fail. This is important because the subaccount defaults to 'test'. When you visit Mandrillapp.com to get your API key, set up a subaccount called 'test' (all lowercase). Once you're done testing your mail system, you can create a new subaccount and delete the 'test' account so all the test emails won't be cluttering up the reports. At that point, you should change the subaccount specified in the properties.

Message Structure

Messages sent through MandrillX cannot contain MODX tags. In other words, all MODX tags must be resolved before the message is set with addHTML(). The message can, however, contain user placeholders. The value for these will be different for every message because they are user-specific. The user placeholders must be in the form {{+placeholderName}}. These will be converted to Mandrill-style placeholders (*|placeholderName|*) just before the message is transmitted to Mandrill.

The addUser() Method

Users who will receive mail must be added with addUser(). The argument to addUser() is an associative array of field names and values. The name and email fields are required. Any other fields will be treated as merge fields and will be used to replace the user-specific placeholders. If there is no user placeholder matching a sent field, it will be ignored. Important: Mandrill requires that each email address be unique when sending a particular message. If there are duplicate email addresses, the user placeholders will not be set correctly.

Send

Once all the users have been added with addUser() and the message text has been set, sending the message is simple a matter of calling $mx->sendMessage(). The method returns an array of results that you can analyze or dump, but once you have things working, you'll find that the reports you'll see at Mandrill are much more useful. In fact, the return value will report success for sends to phony email addresses as long as they are well-formed.

Additional Properties

There are some optional properties you can include in the $scriptProperties array. The first of these is headers. The reply_to header is set automatically, but if you want to send more headers than that, you can include them in the the headers member in this form:

    $scriptProperties['headers'] = 'header1:header1Value,header2:header2Value';

The other optional properties can be set in your account settings at Mandrill. In MandrillX, they default to null, which means that the account settings will be used. If you set them to true or false, they will override the account values:

    track_opens
    track_clicks
    auto_html
    auto_text
    inline_css
    url_strip_qs
    preserve_recipients
    view_content_link
    bcc_address
    tracking_domain
    signing_domain
    return_path_domain

Setting the Message Content

How you handle setting the message content depends on when you want to set the content and whether you want to send a multi-part message with a plain text version attached.

You can set the message's HTML content by adding an 'html' member to the $scriptProperties array with the HTML content as its value. It should be added to the array before calling the MandrillX constructor. Often, however, you'll want to send the HTML content later, after you make some modifications to it. In that case you can just call $mx->setHTML($msg), where $msg is the HTML content you want for the message.

What about sending Multi-part message with a text version as well? There are actually several ways to handle this. One is just to set the 'auto_text' setting at Mandrill to true or set the 'auto_text' property to true. Mandrill will automatically strip the HTML tags and add the plain text version to the message. This is the most memory-efficient method.

You may prefer to do the plain text conversion yourself. Notify, for example, uses the html2text class to do the conversion. It produces nicely formatted text with all links appearing as references at the end of the text. If you do the conversion yourself, you can add a 'text' member to the $scriptProperties array, or you can call mx->setText($msg) at any time before the message is actually sent. In that case, you'll want to have the auto_text option turned *off* at Mandrill.

Using a Tpl Chunk for the Message

This works very well. If you do it properly, any MODX tags in the chunk will be processed as it is retrieved. User placeholders in the form {{+placeholderName}} will be left alone because they are not MODX tags. If your message refers to a Resource, you'll need to set any resource-specific placeholders before retrieving the chunk with getChunk(). That goes for TVs as well.

See the core/components/mandrilx/docs/mandrill-example.php file for an example. It uses the MandrillExampleTpl chunk which is installed with MandrillX.

 

My book, MODX: The Official Guide - Digital Edition is now available here. The paper version of the book is available from Amazon.

If you have the book and would like to download the code, you can find it here.

If you have the book and would like to see the updates and corrections page, you can find it here.

MODX: The Official Guide is 772 pages long and goes far beyond this web site in explaining beginning and advanced MODX techniques. It includes detailed information on:

  • Installing MODX
  • How MODX Works
  • Working with MODX resources and Elements
  • Using Git with MODX
  • Using common MODX add-on components like SPForm, Login, getResources, and FormIt
  • MODX security Permissions
  • Customizing the MODX Manager
  • Using Form Customization
  • Creating Transport Packages
  • MODX and xPDO object methods
  • MODX System Events
  • Using PHP with MODX

Go here for more information about the book.

Thank you for visiting BobsGuides.com

  —  Bob Ray