Search code examples
phpmailchimpmandrill

Dynamic attachments mandrill


I am new to mandrill and just wondering can I use mandrill to create templates that I can send to recipients as attachments. For instance if I wanted to send a downloadable event ticket with dynamic content. I was thinking of designing the event ticket as a template in mandrill.

My code:

$template_name = 'eventTicket';
$template_content = array(
    array(
        'name' => 'example name',
        'content' => 'example content'
         )
);

Solution

  • You can return HTML results using render then use a library like tcpdf to convert the html to pdf which you can then send as an attachment

    <?php
    try {
    $mandrill = new Mandrill('YOUR_API_KEY');
    $template_name = 'Example Template';
    $template_content = array(
        array(
            'name' => 'editable',
            'content' => '<div>content to inject *|MERGE1|*</div>'
        )
    );
    $merge_vars = array(
        array(
            'name' => 'merge1',
            'content' => 'merge1 content'
        )
    );
    $result = $mandrill->templates->render($template_name, $template_content, $merge_vars);
    print_r($result);
    
    // create new PDF document
            $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
            // set font
            $pdf->SetFont('helvetica', '', 10);
            // set image scale factor
            $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
    
            // add a page
            $pdf->AddPage();
            // output the HTML content
            $pdf->writeHTML($result['html'], true, false, true, false, '');
            $file_name = 'filename.pdf';
            $path = $your_upload_path.$file_name;
            $pdf->Output($path,'F');
    
    
    /*
    Array
    (
        [html] => content to inject merge1 content
    )
    */
    } catch(Mandrill_Error $e) {
    // Mandrill errors are thrown as exceptions
    echo 'A mandrill error occurred: ' . get_class($e) . ' - ' . $e->getMessage();
    // A mandrill error occurred: Mandrill_Invalid_Key - Invalid API key
     throw $e;
    }
    ?>