【发布时间】:2012-05-17 18:38:37
【问题描述】:
假设我需要向客户发送包含客户详细信息和订单详细信息的邮件。 我在 html 文件中有模板 html 数据。客户数据在那里,以及订单详细信息也在同一个 html 模板文件中。我的 html 看起来像
<html>
<body>
Hi {FirstName} {LastName},
Here are your orders:
{foreach Orders}
Order ID {OrderID} Quantity : {Qty} <strong>{Price}</strong>.
{end}
</body>
</html>
现在我想用实际值填写所有用 {} 包围的示例关键字,并迭代和填写订单。
我搜索谷歌,发现微软提供了一个名为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 = "
Hello <%Name%> You're from <%Country%>.";
MailMessage msg = md.CreateMailMessage("you@anywhere.com", replacements, body, new System.Web.UI.Control());
通过上面的代码,我们可以用实际值替换伪值,但我不知道如何迭代订单细节并填充订单数据。
所以如果可以使用 MailDefinition 类,那么请指导我如何在循环中迭代并为订单详细信息生成正文。
【问题讨论】:
-
如果第三方库是一个选项,请查看dotLiquid。您可能还想看看我对类似问题的回答:stackoverflow.com/a/28558160/79485
-
如何下载MailDefinition?
-
MailDefinition 是 .NET 的一部分,位于 System.Web 命名空间中。你不需要下载它。
标签: c# email-templates