Sending a mail as both HTML and Plain Text in .net

后端 未结 6 1272
暖寄归人
暖寄归人 2020-12-24 05:12

I\'m sending mail from my C# Application, using the SmtpClient. Works great, but I have to decide if I want to send the mail as Plain Text or HTML. I wonder, is there a way

相关标签:
6条回答
  • 2020-12-24 05:25

    What you want to do is use the AlternateViews property on the MailMessage

    http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews.aspx

    0 讨论(0)
  • 2020-12-24 05:38

    I'm just going to put a note here for anyone that's having problems and finds their way to this page - sometimes, Outlook SMTP servers will reconvert outgoing email. If you're seeing your plain-text body vanish entirely, and nothing but base64-encoded attachments, it might be because your server is reencoding the email. Google's SMTP server does not reencode email - try sending through there and see what happens.

    0 讨论(0)
  • 2020-12-24 05:47

    Just want to add that you can use defined constants MediaTypeNames.Text.Html and MediaTypeNames.Text.Plain instead of "text/html" and "text/plain", which is always a preferable way. It's in System.Net.Mime namespace.

    So in the example above, it would be:

    AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlContent, null, MediaTypeNames.Text.Html);
    
    0 讨论(0)
  • 2020-12-24 05:50

    The MSDN Documentation seems to miss one thing though, I had to set the content type manually, but otherwise, it works like a charm :-)

    MailMessage msg = new MailMessage(username, nu.email, subject, body);
    msg.BodyEncoding = Encoding.UTF8;
    msg.SubjectEncoding = Encoding.UTF8;
    
    AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlContent);
    htmlView.ContentType = new System.Net.Mime.ContentType("text/html");
    msg.AlternateViews.Add(htmlView);
    
    0 讨论(0)
  • 2020-12-24 05:50

    On top of using AlternateViews views to add both the html and the plain text view, make sure you are not also setting the body of the Mail Message object.

    // do not do this: 
    var msg = new MailMessage(model.From, model.To);
    msg.Body = compiledHtml;  
    

    As it will make your email contain the html content in both views, overriding the alternative views.

    0 讨论(0)
  • 2020-12-24 05:50

    For the people(like me) who've had the problem of gmail displaying the plaintext part instead of the html part.

    Gmail seems to always display the last part in your message.

    So if you've added the html part before your plain text part chances are gmail will always show the plain text variant.

    To fix this you can simply add the plain text part before your html part.

    0 讨论(0)
提交回复
热议问题