Skip to content

Sending HTML Emails with System.Net.Mail.MailMessage is more than IsBodyHtml

It seems like lately I’ve been running into a series of things that should be easier than they’re turning out to be. I’m not sure exactly why that is – but I’ve got another fun one to share.

So System.Net.Mail.MailMessage is the object (along with SmtpClient) which are used to send emails. There’s a single property on MailMessage called IsBodyHtml that is supposed to indicate that the body of the HTML should be treated as Html. That’s all fine and good except that my experience is that it doesn’t work consistently. In fact, it rarely works for me. So how do you make it work? Well, you add Alternate views. MailMessage has a property AlternateViews which is a set of alternate views that can be displayed with the message. In order to get a HTML view I had to add a new AlternateView with the encoding of text/html or System.Net.Mime.MediaTypes.Text.Html. So when I want HTML I add this code to the bottom of the place where I’m sending the message:

AlternateView av = AlternateView.CreateAlternateViewFromString(msg.Body, new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Html));

av.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;

msg.AlternateViews.Add(av);

I also generally add one for plain text encoding for those email readers that can’t cope with HTML which can be done by replacing the content type with ‘Text/Plain’ like this:

AlternateView av = AlternateView.CreateAlternateViewFromString(msg.Body, new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain));

av.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;

msg.AlternateViews.Add(av);

Hopefully this will make it easier to figure out what is wrong when you are trying to send HTML email messages and it isn’t working.

1 Comment


Add a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share this: