Search code examples
c#cssemailmvcmailerpremailer

How to move CSS inline with PreMailer.Net whilst using MvcMailer for sending HTML emails


Using MvcMailer, the problem is that our emails are being sent without our CSS as inline style attributes.

PreMailer.Net is a C# Library that can read in an HTML source string, and return a resultant HTML string with CSS in-lined.

How do we use them together? Using the scaffolding example in the MvcMailer step-by-step guide, we start out with this example method in our UserMailer Mailer class:

public virtual MvcMailMessage Welcome()
{
    return Populate(x => {
        x.ViewName = "Welcome";
        x.To.Add("[email protected]");
        x.Subject = "Welcome";
    });
}

Solution

  • Simply install PreMailer.Net via NugGet

    Update the Mailer class:

    public virtual MvcMailMessage Welcome()
    {
        var message = Populate(x => {
            x.ViewName = "Welcome";
            x.To.Add("[email protected]");
            x.Subject = "Welcome";
        });
        message.Body = PreMailer.Net.PreMailer.MoveCssInline(message.Body).Html;
        return message;
    }
    

    Done!