How to send multi-part MIME messages in c#?

Shaul Behr picture Shaul Behr · Mar 30, 2011 · Viewed 14.9k times · Source

I want to send multi-part MIME messages with an HTML component plus a plain text component for people whose email clients can't handle HTML. The System.Net.Mail.MailMessage class doesn't appear to support this. How do you do it?

Answer

Shaul Behr picture Shaul Behr · Mar 30, 2011

D'oh, this is really simple... but I'll leave the answer here for anyone who, like me, came looking on SO for the answer before Googling... :)

Credit to this article.

Use AlternateViews, like so:

//create the mail message
var mail = new MailMessage();

//set the addresses
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");

//set the content
mail.Subject = "This is an email";

//first we create the Plain Text part
var plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain");
//then we create the Html part
var htmlView = AlternateView.CreateAlternateViewFromString("<b>this is bold text, and viewable by those mail clients that support html</b>", null, "text/html");
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);

//send the message
var smtp = new SmtpClient("127.0.0.1"); //specify the mail server address
smtp.Send(mail);