Improve HTML E-mails from WordPress, automagically

HTML e-mails are like wild stallions.  They are really hard to tame.

I have been frustrated by the vastly different ways e-mails from my company’s site (http://www.mooreandgiles.com) render in different clients.  After some research, I decided the trick to fix this would be inlining all CSS styles, as various clients will haphazardly abort style blocks you include in your e-mails.

Being lazy and wanting to the greatest flexibility for modifying templates in the future, I came up with a way to automatically process e-mails and inline their styles as they leave.   As this hooks into wp_mail, it should work with most plugins that send HTML e-mails.  Some may go around WordPress and use PHP mail…I can’t help you there.

In your theme functions file, add this:

add_filter('wp_mail', 'html_email_prep');
 
function html_email_prep($email) {
	if(strpos($email['headers'], "html") != false )
	{
		$message = $email['message'];
 
		//Grab CSS block
		require_once TEMPLATEPATH.'/css_to_inline_styles.php';
 
		$cssConverter = new CSSToInlineStyles();
		$cssConverter->setCleanup(true);
		$cssConverter->setHTML($message);
		$cssConverter->setUseInlineStylesBlock(true);
 
		$new_html = $cssConverter->convert();
 
		$email['message'] = $new_html;
	}
 
	return $email;
}

And, simply dropp css_to_inline_styles.php in your theme folder. You may download it here: http://blog.verkoyen.eu/blog/p/detail/convert-css-to-inline-styles-with-php

With this in place, it will automatically parse outgoing e-mail messages. It will find the style block and inline each style, automagically. This instantly fixed most of the rendering problems I was having in various clients.

It automatically excludes e-mails that don’t have HTML. I have seen the class bork up one HTML template, but making a minor change to the markup avoided the problem easily. Make sure you test.

  • http://twitter.com/Flor_Coppola Flor Coppola

    Thanks for your example!

    • Anonymous

      My pleasure. Glad it was useful.

  • Pete

    Thanks for this.  Haven’t had a chance to check it out, but it looks like it’ll point me in the right direction.  I noticed the download link is broken – the current one seems to be https://github.com/tijsverkoyen/CssToInlineStyles