Custom email templates with CakePHP

I was working on a CakePHP app for an internal company service. We had a need to send emails that come from custom templates. Not just the usual email template files. This needed to allow customers to be able to upload or import HTML emails and the app would push them out. We also wanted to give them the ability to insert custom data tags for things like names, etc. So, I decided I wanted to use Mustache templates to achieve this. It would be perfect because it will also allow them to create their own custom data fields, and then insert them straight into the email templates. I added Mustahce as a vendor plugin by putting it into the main Vendor folder. Then you just need to pass it the HTML template code and an array of data variables.

App::import('Vendor', 'mustache/Engine');
$m = new Mustache_Engine;
$vars = array(
    'firstname' => 'John'
    'lastname' => 'Doe'
);
$html = $m->render($template, $vars);

This worked great, and fulfilled that need. Then, thinking back to my experience in building tons and tons of HTML emails, I knew that some email clients, like Gmail, love to strip out any style tags. You need to put all of your styles inline with your tags in HTML emails. So, now I needed a way to pre process the template and place all the styles inline. Usually you just use a pre mailer service like

MailChimp's inlineCss api call, or Premailer to do this. However, I needed to do this on the fly before sending it out. I could have just used MailChimp's api service and called it a day, but I didn't want to rely on a third party service which could add delays and possible future problems. So, I did some searching and found a nice little class called Emogrifier. This will let you pass in raw HTML with blocks of CSS in style tags, or a separate CSS file. It does a great job and integrates into Cake just as easily as Mustache.

App::import('Vendor', 'emogrifier/emogrifier');
$e = new Emogrifier($html, $css);
$inlined_html = $e->emogrify();

You pass the HTML into the constructor when instantiating a new instance of the Emogrifier class. The second parameter is optional and can be used to pass in additional CSS styles. Emogrifier will use this CSS, and then append any CSS inside the HTML and then inline it and return the result. So, there you have it. Custom email templates built and processed on the fly. Send it out with your email service of choice.