首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在C#中生成HTML电子邮件正文

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

Stack Overflow用户
提问于 2009-05-20 08:07:27
回答 8查看 243.3K关注 0票数 120

有没有更好的方法在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>");

等等,等等?

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 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的博客文章。

票数 185
EN

Stack Overflow用户

发布于 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();
票数 29
EN

Stack Overflow用户

发布于 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

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/886728

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档