How can I set the MailMessage's body with a HTML file ?
2 Answers
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...
//...
}
-
11So, just to specify, this answer corresponds with
System.Web.Mail.MailMessage
. When attempting to set theBodyFormat
, I was having issues because Reflector was telling me it wasn't there. Reason being, I was usingSystem.Net.Mail.MailMessage
(in that class, there's abool
flag calledIsBodyHtml
that you can set instead). Also, seems that if all things being equal,System.Net.Mail
is suggested for use: stackoverflow.com/q/64599/324527 Jul 11, 2012 at 15:37 -
4This has changed now. You should use "myMail.IsBodyHtml = true;" Nov 19, 2015 at 18:32
-
What if I want to change the content of the HTML code? For ex:
Dear *value_from_C#_variable*
Dec 20, 2018 at 13:04
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.
img
link to a web source, which many email clients won't display). Edit: You can of course read the html file withFile.ReadAllText
, which you'd use as in the links.