JackofAll
JackofAll

Reputation: 537

How to set Body format to HTML in C# Email

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

var fromAddress = new MailAddress("[email protected]", "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 = "[email protected]",
    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?

Upvotes: 2

Views: 15396

Answers (3)

Ashwini
Ashwini

Reputation: 747

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

Upvotes: 0

canon
canon

Reputation: 41675

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
})

Upvotes: 10

Prakash Chennupati
Prakash Chennupati

Reputation: 3226

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 = "[email protected]";
    myMail.To = "[email protected]";
    myMail.Subject = "HTML Message";
    myMail.BodyFormat = MailFormat.Html;

    myMail.Body = reader.ReadToEnd();  // Load the content from your file...
    //...
}

Upvotes: 0

Related Questions