2013-04-01 57 views
1

我有以下的代码来创建和发送电子邮件:如何正文格式设置为HTML在C#电子邮件

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

我如何能在邮件正文设置为HTML?

+1

你也应该把'var smtp = new SmtpClient'放在'using'中。 –

回答

8

MailMessage. IsBodyHtml(从MSDN):

获取或设置指示该电子邮件消息主体是否处于 的Html的值。

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

只需设置MailMessage.BodyFormat属性MailFormat.Html,然后倾倒你的HTML文件的内容到MailMessage.Body属性:

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

设置IsBodyHtml为true。然后,您的邮件将以HTML格式呈现。

+0

为什么你会在近一年后发布重复[答案](http://stackoverflow.com/a/15749389/621962)? – canon