2013-04-01 54 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