Mandrill email attachments file path

Manu picture Manu · Mar 5, 2013 · Viewed 24k times · Source

I am trying to add some attachments to an email that is being sent using the mandrill api via a php wrapper. I have tried a number of different things to try to successfully attach the file but to no avail. I am using cakephp 2.x but I don't think that has any particular significance in this instance (maybe it does?!). I am using the php wrapper maintained by mandrill at https://bitbucket.org/mailchimp/mandrill-api-php

Here is the code:

$mandrill = new Mandrill(Configure::read('Site.mandrill_key'));
    $params = array(
        'html' => '
            <p>Hi '.$user['User']['name'].',</p>
            <p>tIt is that time of the year again.<br />
            <a href="http://my-site.com/members/renewal">Please login to the website members area and upload your renewal requirements</a>.</p>
            <p>Kind regards.</p>',
        "text" => null,
        "from_email" => Configure::read('Site.email'),
        "from_name" => Configure::read('Site.title'),
        "subject" => "Renewal Pending",
        "to" => array(array('email' => $user['User']['email'])),
        "track_opens" => true,
        "track_clicks" => true,
        "auto_text" => true,
        "attachments" => array(
            array(
                'path' => WWW_ROOT.'files/downloads/renewals',
                'type' => "application/pdf",
                'name' => 'document.pdf',
            )
        )
    );

    $mandrill->messages->send($params, true);

}

This shows that an attachment has been added to the email and is a pdf but the actual pdf has not been attached. I also tried by adding the path directly onto the file as in:

"attachments" => array(
            array(
                'type' => "application/pdf",
                'name' => WWW_ROOT.'files/downloads/renewals/document.pdf',
            )

I have googled and read every article I can find but cannot find any specific reference as to how I should specify the path for mandrill to correctly attach my attachment.

Any help will be greatly appreciated.

Answer

Manu picture Manu · Mar 6, 2013

OK. So thanks to Kaitlin for her input. The PHP way to deal with this is to get the file and then base64_encode it:

$attachment = file_get_contents(WWW_ROOT.'files/downloads/file.pdf');
$attachment_encoded = base64_encode($attachment); 

and then in the attachments part of the mandrill array you pass the :

"attachments" => array(
        array(
            'content' => $attachment_encoded,
            'type' => "application/pdf",
            'name' => 'file.pdf',
        )

So easy! Thanks again Kaitlin!