23

How can I set the MailMessage's body with a HTML file ?

A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
Paul
  • 12,359
  • 20
  • 64
  • 101
  • Here's [a simple example](http://www.example-code.com/csharp/SimpleSendHtmlEmail.asp). And [here's one that includes an embedded image](http://www.example-code.com/csharp/HtmlEmbeddedImage.asp) (as opposed to an `img` link to a web source, which many email clients won't display). Edit: You can of course read the html file with `File.ReadAllText`, which you'd use as in the links. – Sam Harwell Jul 20 '09 at 20:33

2 Answers2

49

Just set the MailMessage.BodyFormat property to MailFormat.Html, and then dump the contents of your html file to the MailMessage.Body property:

using (StreamReader reader = File.OpenText(htmlFilePath)) // Path to your 
{                                                         // HTML file
    MailMessage myMail = new MailMessage();
    myMail.From = "from@microsoft.com";
    myMail.To = "to@microsoft.com";
    myMail.Subject = "HTML Message";
    myMail.BodyFormat = MailFormat.Html;

    myMail.Body = reader.ReadToEnd();  // Load the content from your file...
    //...
}
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • 11
    So, just to specify, this answer corresponds with `System.Web.Mail.MailMessage`. When attempting to set the `BodyFormat`, I was having issues because Reflector was telling me it wasn't there. Reason being, I was using `System.Net.Mail.MailMessage` (in that class, there's a `bool` flag called `IsBodyHtml` that you can set instead). Also, seems that if all things being equal, `System.Net.Mail` is suggested for use: http://stackoverflow.com/q/64599/324527 – Mattygabe Jul 11 '12 at 15:37
  • 4
    This has changed now. You should use "myMail.IsBodyHtml = true;" – OrangeKing89 Nov 19 '15 at 18:32
  • What if I want to change the content of the HTML code? For ex: `Dear *value_from_C#_variable*` – Prashant Pimpale Dec 20 '18 at 13:04
24

I case you are using System.Net.Mail.MailMessage, you can use:

mail.IsBodyHtml = true;

System.Web.Mail.MailMessage is obsoleted but if using it: mail.BodyFormat works.

A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128