与使用Stringbuilder进行以下操作相比,有没有一种更好的方法可以用C#生成HTML电子邮件(用于通过System.Net.Mail发送)?
string userName = "John Doe"; StringBuilder mailBody = new StringBuilder(); mailBody.AppendFormat("<h1>Heading Here</h1>"); mailBody.AppendFormat("Dear {0}," userName); mailBody.AppendFormat("<br />"); mailBody.AppendFormat("<p>First part of the email body goes here</p>");
等等等等?
您可以使用MailDefinition类。
这是您的用法:
MailDefinition md = new MailDefinition(); md.From = "test@domain.com"; md.IsBodyHtml = true; md.Subject = "Test of MailDefinition"; ListDictionary replacements = new ListDictionary(); replacements.Add("{name}", "Martin"); replacements.Add("{country}", "Denmark"); string body = "<div>Hello {name} You're from {country}.</div>"; MailMessage msg = md.CreateMailMessage("you@anywhere.com", replacements, body, new System.Web.UI.Control());
另外,我已经写了一篇博客文章,介绍如何使用MailDefinition类使用模板在C#中生成HTML电子邮件正文。