Search code examples
phpmailchimpmandrill

Simple php function to send an email with Mandrill


What is the easiest way to send an email via Mailchimp's Mandrill service (using the API).

Here's the send method: https://mandrillapp.com/api/docs/messages.html#method=send

Here's the API wrapper: https://bitbucket.org/mailchimp/mandrill-api-php/src/fe07e22a703314a51f1ab0804018ed32286a9504/src?at=master

But I can't figure out how to make an PHP function that will send and email via Mandrill.

Can anyone help?


Solution

  • We also have an official API wrapper for PHP, which is available on Bitbucket or via Packagist, which wraps the Mandrill API for you.

    If your Mandrill API key is stored as an environment variable, here's a simple example of sending using a template, with some merge variables and metadata:

    <?php
    require 'Mandrill.php';
    
    $mandrill = new Mandrill();
    
    // If are not using environment variables to specific your API key, use:
    // $mandrill = new Mandrill("YOUR_API_KEY")
    
    $message = array(
        'subject' => 'Test message',
        'from_email' => '[email protected]',
        'html' => '<p>this is a test message with Mandrill\'s PHP wrapper!.</p>',
        'to' => array(array('email' => '[email protected]', 'name' => 'Recipient 1')),
        'merge_vars' => array(array(
            'rcpt' => '[email protected]',
            'vars' =>
            array(
                array(
                    'name' => 'FIRSTNAME',
                    'content' => 'Recipient 1 first name'),
                array(
                    'name' => 'LASTNAME',
                    'content' => 'Last name')
        ))));
    
    $template_name = 'Stationary';
    
    $template_content = array(
        array(
            'name' => 'main',
            'content' => 'Hi *|FIRSTNAME|* *|LASTNAME|*, thanks for signing up.'),
        array(
            'name' => 'footer',
            'content' => 'Copyright 2012.')
    
    );
    
    print_r($mandrill->messages->sendTemplate($template_name, $template_content, $message));
    
    ?>