Sending mail both HTML and plain text to .net

I am sending mail from my C # application using SmtpClient. Works great, but I have to decide if I want to send mail as plain text or HTML. I wonder if there is a way to send both? I think this is called multipart.

I did a bit of work with Google, but most of the examples didn’t actually use SmtpClient, but they made up the entire SMTP body, which is a bit scary, so I wonder if something is built in the .NET Framework 3.0?

If not, is there a really well-used / reliable third-party library for sending emails?

+50
c #
Sep 04 '08 at 21:03
source share
6 answers

What you want to do is use the AlternateViews property in MailMessage

http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews.aspx

+44
Sep 04 '08 at 21:07
source share

The MSDN documentation seems to have missed one thing, although I had to set the content type manually, but otherwise it works like a charm :-)

MailMessage msg = new MailMessage(username, nu.email, subject, body); msg.BodyEncoding = Encoding.UTF8; msg.SubjectEncoding = Encoding.UTF8; AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlContent); htmlView.ContentType = new System.Net.Mime.ContentType("text/html"); msg.AlternateViews.Add(htmlView); 
+56
Sep 04 '08 at 21:57
source share

I just want to add that you can use certain MediaTypeNames.Text.Html and MediaTypeNames.Text.Plain instead of "text/html" and "text/plain" , which is always preferable. It is located in the System.Net.Mime namespace.

So, in the above example, this would be:

 AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlContent, null, MediaTypeNames.Text.Html); 
+29
Aug 24 '09 at 15:52
source share

I am just going to write here for everyone who has problems and find their way to this page - sometimes Outlook SMTP servers will convert outgoing emails. If you see that your body of plain text disappears completely, and nothing but base64-based attachments, it is possible because your server will transcode the email. Google SMTP server does not rewrite email - try sending there and see what happens.

+11
Sep 28 '09 at 17:38
source share

In addition to AlternateViews for adding both html and plain text, make sure you do not set the body of the Mail Message object either .

 // do not do this: var msg = new MailMessage(model.From, model.To); msg.Body = compiledHtml; 

Once your email contains html content in both views, override the alternative views.

+7
Jun 25 '16 at 0:12
source share

For people (like me) who had a gmail problem displaying a piece of plaintext instead of a html part.

Gmail always seems to display the last part of your message.

So, if you added the html part in front of your plain text snippet, perhaps gmail will always show the plaintext option.

To fix this, you can simply add a piece of plain text in front of your html part.

+4
Oct. 20 '17 at 12:55 on
source share



All Articles