Skip to content Skip to sidebar Skip to footer

Correct Syntax For Generating Html Email Using Alternateview

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 re-coding an old conso

Solution 1:

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

Post a Comment for "Correct Syntax For Generating Html Email Using Alternateview"