在 C# 中生成 HTML 电子邮件正文

新手上路,请多包涵

在 C# 中生成 HTML 电子邮件(通过 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>");

等等等等?

原文由 Rob 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 742
2 个回答

您可以使用 MailDefinition 类

这是你如何使用它:

 MailDefinition md = new MailDefinition();
md.From = "test@domain.example";
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.example", replacements, body, new System.Web.UI.Control());

此外,我还写了一篇关于如何 使用 MailDefinition 类使用模板在 C# 中生成 HTML 电子邮件正文的博文

原文由 MartinHN 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 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();

对于包含创建样式属性的大量 HTML,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();

原文由 AnthonyWJones 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题