I am using Postal to render MVC Razor views and send them via email. I have a custom CSS that I have defined specifically for the email views. Currently I am including them as follows:
@Styles.Render("~/Content/EmailStyles.css")
However, this only includes the relative link to the stylesheet, which will not work in an email:
<link href="/Content/EmailStyles.css" rel="stylesheet"/>
I want to include the stylesheet inline so that it functions properly in the email. What is the best way to render the contents of a file-based resource within an MVC view?
Upvoted Paul d'Aoust's answer, but I found this version of his helper method to work a little better for me (wouldn't try to encode things like quotes in the CSS):
I guess you will need to have a custom helper for that. On top of my head, there is no such a method to render the css path including the absolute path of the website.
e.g. http:www.example.com/css/EmailStyles.css
I had the same question myself, and came across Premailer.Net. It looks like the library you need. Here's what you'd have to do:
Create an extension method to help you embed your CSS into your page; there's an answer on a question on how to embed HTML in a Razor view that should help you. I've modified it for embedding CSS:
Then in your Razor template, just go:
to embed your CSS text.
Install the Premailer.Net package in your project; you can get it through NuGet.
Render your Razor view into a string (I guess that's what Postal is for in your process? I believe RazorEngine can also do that).
Run the string through Premailer.Net:
Send as an e-mail!
I've been using this technique in production for a while now, and it seems to be working quite well.
Edit: Remember that styles on pseudo-elements can't be inlined because they don't exist in the markup. I've also noticed the odd little bug in Premailer.Net -- I think their specificity and cascade rules aren't perfectly conformant. Still, it's pretty good and it's one more piece of code I didn't have to write!