Created
November 27, 2014 00:57
-
-
Save paulduran/91dd14c0eecc6b1ff22f to your computer and use it in GitHub Desktop.
Premailer with Postal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Weird though my message.IsBodyHtml
is always false, but the code works for some reason. Saved me lots of time, thanks!
@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
@paulduran I found this from here.
I found a bug: if the email has an image then it won't be included.
remove this:
add this: