Search code examples
c#htmlasp.netemailplaintext

ASP.net / C# Email with AlternateViews to Show HTML not the PlainText


Currently I can properly send an HTML email with ASP.net. I noticed that using a spam tester such https://www.mail-tester.com/ would give a better score if you supplied both a plain text view as well as the HTML view. So i decided to try to add the alternate views. My issues is that if I try and add a plain text view it seems to override the HTML View. Here is the code that works perfectly fine for setting up my HTML only view:

    message.IsBodyHtml = true;
    message.BodyEncoding = Encoding.UTF8;
    message.BodyTransferEncoding = TransferEncoding.Base64;
    message.Body = "<html lang=\"en\"><head><meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"></head><body>" + message.Body + "</body></html>";

Now if I try to add the plain view Gmail seems to only want to display the plain text view and not the HTML view. Is there anyway to set which view is default? Here is my plain text view code:

    message.IsBodyHtml = true;
    message.BodyEncoding = Encoding.UTF8;
    message.BodyTransferEncoding = TransferEncoding.Base64;
    message.Body = "<html lang=\"en\"><head><meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"></head><body>" + message.Body + "</body></html>";

    //first we create the Plain Text part
    var plainView = AlternateView.CreateAlternateViewFromString(HtmlToPlainText(message.Body), Encoding.UTF8, MediaTypeNames.Text.Plain);
    ////then we create the Html part
    var htmlView = AlternateView.CreateAlternateViewFromString(message.Body, Encoding.UTF8, MediaTypeNames.Text.Html);
    message.AlternateViews.Add(htmlView);
    message.AlternateViews.Add(plainView);

I have tried removing first displayed code for the body and setting the body to empty string so that it only adds both of the alternate views and that did not work. I believe I covered all permutations of the code and still nothing. Like I said it works perfectly for HTML only and it works with html alternate view but not when adding the plain text view.


Solution

  • You create the plain text version first but you add it after the HTML version. According to the reference below, the plain text version must come first.

    You may also notice in the code example that IsBodyHtml is set separately for each version: it is falsefor the plain text version and true for the HTML version.

    Correct Syntax for Generating HTML Email using AlternateView