Correct Syntax for Generating HTML Email using AlternateView

前端 未结 1 1953
囚心锁ツ
囚心锁ツ 2021-01-14 08:25

I\'m trying to use the AlternateView to cater for both HTML and Text clients. I would prefer to use HTML and only fall back to text where necessary. I started r

相关标签:
1条回答
  • 2021-01-14 09:01

    UPDATE - 09-30-2019: Microsoft updated the documentation for this.

    As I guessed, I had to explicitly provide a plain text and HTML version of the message body. The MSDN documentation was not very helpful. Here's a snippet of the code I created to get this working:

    // args[0] - Subject
    // args[1] - Plain text body content
    // args[2] - HTML body content
    // args[3] - RfpID
    
    textMessage += "\n\nIf you no longer wish to receive notifications, you can "
        + "unsubscribe and your details will be removed from our system:\n"
        + "http://example.com/apps/vendorreg/unsubscribe.aspx?unsub=" + hash + "\n\n"
        + "Example Website Policies:\n"
        + "http://example.com/doc/help/policies/help_website_policies";
    
    // Important: Mime standard dictates that text version must come first 
    using (AlternateView textPart = 
        AlternateView.CreateAlternateViewFromString(textMessage, null, "text/plain"))
    {
        textPart.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
        mailMessage.AlternateViews.Add(textPart);
        mailMessage.IsBodyHtml = false;
        mailMessage.Body = textMessage;
    }
    
    htmlMessage += Environment.NewLine + Environment.NewLine
        + "If you no longer wish to receive notifications, you can "
        + "unsubscribe and your details will be removed from our system:"
        + Environment.NewLine 
        + "http://example.com/apps/vendorreg/unsubscribe.aspx?unsub=" + hash
        + Environment.NewLine + Environment.NewLine
        + "Example.com Website Policies:" 
        + Environment.NewLine
        + "http://example.com/doc/help/policies/help_website_policies";
    
    using (AlternateView htmlPart = 
        AlternateView.CreateAlternateViewFromString(htmlMessage,
        System.Text.Encoding.UTF8, "text/html"))
    {
        htmlPart.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
        mailMessage.AlternateViews.Add(htmlPart);
        mailMessage.IsBodyHtml = true;
        mailMessage.Body = htmlMessage;
    }
    
    // Send email
    
    0 讨论(0)
提交回复
热议问题