Correct Syntax for Generating HTML Email using AlternateView

╄→гoц情女王★ 提交于 2019-12-01 09:02:35

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!