有没有更好的方法在C#中生成超文本标记语言电子邮件(通过System.Net.Mail发送),而不是使用Stringbuilder来做以下事情:
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>");
等等,等等?
发布于 2009-05-20 08:13:08
您可以使用MailDefinition class。
下面是它的使用方法:
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());
此外,我还写了一篇关于如何generate HTML e-mail body in C# using templates using the MailDefinition class的博客文章。
发布于 2009-05-20 08:12:30
使用System.Web.UI.HtmlTextWriter类。
StringWriter writer = new StringWriter();
HtmlTextWriter html = new HtmlTextWriter(writer);
html.RenderBeginTag(HtmlTextWriterTag.H1);
html.WriteEncodedText("Heading Here");
html.RenderEndTag();
html.WriteEncodedText(String.Format("Dear {0}", userName));
html.WriteBreak();
html.RenderBeginTag(HtmlTextWriterTag.P);
html.WriteEncodedText("First part of the email body goes here");
html.RenderEndTag();
html.Flush();
string htmlString = writer.ToString();
对于大量包含样式属性创建的超文本标记语言,HtmlTextWriter可能是最佳选择。然而,它的使用可能有点笨拙,一些开发人员希望标记本身易于阅读,但反常的是,HtmlTextWriter在缩进方面的选择有点奇怪。
在本例中,您还可以非常有效地使用XmlTextWriter:
writer = new StringWriter();
XmlTextWriter xml = new XmlTextWriter(writer);
xml.Formatting = Formatting.Indented;
xml.WriteElementString("h1", "Heading Here");
xml.WriteString(String.Format("Dear {0}", userName));
xml.WriteStartElement("br");
xml.WriteEndElement();
xml.WriteElementString("p", "First part of the email body goes here");
xml.Flush();
发布于 2015-02-17 17:04:54
我使用dotLiquid来完成这个任务。
它接受一个模板,并用匿名对象的内容填充特殊的标识符。
//define template
String templateSource = "<h1>{{Heading}}</h1>Dear {{UserName}},<br/><p>First part of the email body goes here");
Template bodyTemplate = Template.Parse(templateSource); // Parses and compiles the template source
//Create DTO for the renderer
var bodyDto = new {
Heading = "Heading Here",
UserName = userName
};
String bodyText = bodyTemplate.Render(Hash.FromAnonymousObject(bodyDto));
它也适用于集合,参见some online examples。
https://stackoverflow.com/questions/886728
复制相似问题