Skip to content

Instantly share code, notes, and snippets.

@paulduran
Created November 27, 2014 00:57
Show Gist options
  • Save paulduran/91dd14c0eecc6b1ff22f to your computer and use it in GitHub Desktop.
Save paulduran/91dd14c0eecc6b1ff22f to your computer and use it in GitHub Desktop.
Premailer with Postal
public class MailSender
{
static MailSender()
{
var viewRenderer = new EmailViewRenderer(ViewEngines.Engines) {EmailViewDirectoryName = "UserMailer"};
var emailParser = new EmailParser(viewRenderer);
Email.CreateEmailService = ()=>new EmailService(viewRenderer, new PremailerEmailParser(emailParser), ()=>new SmtpClient());
}
public void SendEmail()
{
// do all your normal email stuff
}
private class PremailerEmailParser : IEmailParser
{
private readonly IEmailParser wrapped;
public PremailerEmailParser(IEmailParser wrapped)
{
this.wrapped = wrapped;
}
public MailMessage Parse(string emailViewOutput, Email email)
{
var message = wrapped.Parse(emailViewOutput, email);
if (message.IsBodyHtml)
{
message.Body = PreMailer.Net.PreMailer.MoveCssInline(message.Body).Html;
}
for(var i = 0 ; i < message.AlternateViews.Count ; i++)
{
var av = message.AlternateViews[i];
if (av.ContentType.MediaType == MediaTypeNames.Text.Html)
{
av.ContentStream.Position = 0;
var content = new StreamReader(av.ContentStream).ReadToEnd();
content = PreMailer.Net.PreMailer.MoveCssInline(content).Html;
message.AlternateViews[i] = AlternateView.CreateAlternateViewFromString(content, av.ContentType);
}
}
return message;
}
}
}
@denisz1
Copy link

denisz1 commented Feb 28, 2015

Weird though my message.IsBodyHtml is always false, but the code works for some reason. Saved me lots of time, thanks!

@paulduran
Copy link
Author

@denisz1 thanks for the tip! We haven't needed to use images yet but your mod will certainly help when we do

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment