Search code examples
c#htmlcssasp.netpremailer

How do I set up a C# project to inline css into HTML from a local .css file? Can PreMailer.Net do this?


I'm trying to update an email templating system to allow for the use of external .css files, rather than having to write all styles inline. My project is in ASP.NET and as far as I can tell, the most used and feature-rich inliner is PreMailer.Net, though I'm open to using a different package if there's one that would better suit my needs. Here's a quick sketch of what I'm trying to do:

Filesystem

G:/templates/
  index.html
  style.css

inliner.cs

string htmlSource = File.ReadAllText("G:\\templates\\index.html");
var uri = new Uri("G:\\templates\\");
var result = PreMailer.MoveCssInline(uri, htmlSource);

index.html

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href='style.css'>
    </head>
    <body>
    </body>
</html>

When I run this code - I get the following error:

Unable to cast object of type 'System.Net.FileWebResponse' to type 'System.Net.HttpWebResponse'.

It's unclear to me based on the documentation if PreMailer.Net supports this use-case. It claims that you can use a relative URL if you specify a BaseUri parameter. The C# code running PreMailer.Net has the necessary context and access to that file path, as evidenced by the fact that it could read the HTML file into a string.


Solution

  • This issue appears to be fixed in the just released 2.1.1 as per this GitHub issue:

    Add support on fetching Uri with local filepath like "file:///C:/website/style.css"

    It's required when we optimize the performance by fetching the local resource internally instead of making external web request towards internal resource. e.g. As I know the css is actually inside the local storage, it make sense to just make a fast local fetch ("file:///C:/website/style.css") instead of external web request ("https://www.example.com/style.css")

    So I can now initialize a PreMailer instance with BaseUri "file:///" + new Uri(System.Web.Hosting.HostingEnvironment.MapPath("~/"), UriKind.Absolute)

    It's how I boost the performance for my client, just share my code here.