Being able to make CSS inline is something you need all the time when sending HTML e-mails. HTML E-mails simply don’t render perfectly in all e-mail clients if you don’t make all your styles inline.
Campaign Monitor introduced the ability to make CSS inline years ago, and it just works. They use the premailer Ruby project to do this, and it seems to work perfectly. You can edit your HTML e-mails using styles embedded inside the HTML document’s <head> tag, and they automatically make the CSS inline on all elements that match your selectors.
At the end of my latest blog post on How to Send HTML E-mail from an ASP.NET MVC Controller, I wrote that I’d like to combine the ActionMailer.Net library with the premailer Ruby project, to be able to send great HTML e-mails from an application, that renders well in all e-mail clients.
I honestly didn’t want to combine ASP.NET MVC with a Ruby project. I can’t image all the hacks necessary to make it work. Eventually, I’d probably start a process from ASP.NET that runs the Ruby script – but it’s still a hack in my opinion.
That made me search the .Net community to see if I could find anything similar for .Net, but I didn’t succeed. But instead I found two interesting things:
And that is exactly what it takes to make CSS inline. I added code to the CSS parser, so that it would merge the style block, if an element already had inline styles specified, and packed the two project into my own solution, called PreMailer.NET.
It works like this:
string htmlSource = File.ReadAllText(@"C:\Workspace\testmail.html"); PreMailer pm = new PreMailer(); string premailedOutput = pm.MoveCssInline(htmlSource, false);
The premailedOutput variable contains e-mail mark-up ready to send.