How to set Body format to HTML in C# Email

风流意气都作罢 提交于 2020-01-05 04:20:08

问题


I have the following code to create and send an email:

var fromAddress = new MailAddress("email@address.com", "Summary");
var toAddress = new MailAddress(dReader["Email"].ToString(), dReader["FirstName"].ToString());
const string fromPassword = "####";
const string subject = "Summary";
string body = bodyText;

//Sets the smpt server of the hosting account to send
var smtp = new SmtpClient
{
    Host = "smpt@smpt.com",
    Port = 587,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)                        
};
using (var message = new MailMessage(fromAddress, toAddress)
{                       
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}

How can I set the message body to HTML?


回答1:


MailMessage.IsBodyHtml (from MSDN):

Gets or sets a value indicating whether the mail message body is in Html.

using (var message = new MailMessage(fromAddress, toAddress)
{                       
    Subject = subject,
    Body = body,
    IsBodyHtml = true // this property
})



回答2:


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...
    //...
}



回答3:


Set mailMessage.IsBodyHtml to true. Then your mail message will get rendered in HTML format.



来源:https://stackoverflow.com/questions/15749368/how-to-set-body-format-to-html-in-c-sharp-email

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!