Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 585
Shaul Behr Avatar asked Mar 30 '11 08:03

Shaul Behr


1 Answers

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); 
like image 115
Shaul Behr Avatar answered Oct 05 '22 06:10

Shaul Behr