如何使用电子邮件模板发送电子邮件 [英] how to send email wth email template c#

查看:118
本文介绍了如何使用电子邮件模板发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我需要向客户发送包含客户详细信息和他的订单详细信息的邮件。
我在html文件中有模板html数据。在同一html模板文件中也有客户数据以及订单明细。我的html外观

suppose i need to send mail to customer with customer detail and his order detail. i have template html data in a html file.customer data is there and as well as order detail is also there in same html template file. my html look like

<html>
<body>
Hi {FirstName} {LastName},

Here are your orders: 
{foreach Orders}
    Order ID {OrderID} Quantity : {Qty} <strong>{Price}</strong>. 
{end}

</body>
</html>

现在我想用实际值填充所有用{}包围的示例关键字,并进行迭代和填充订单。

now i want to fill up all sample keyword surrounded with {} with actual value and also iterate and fill up orders.

我在Google上搜索时发现,Microsoft提供了一个名为 MailDefinition
的类,通过该类我们可以动态生成邮件正文。我也得到了示例代码,例如

i search google and found that microsoft provide a class called MailDefinition by which we can generate mail body dynamically. i got a sample code also like

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

通过上述代码,我们可以将伪值替换为实际值,但是我不知道如何迭代订单明细并填充订单数据。

by the above code we can replace pseudo value with actual value but i don't know how iterate in Orders detail and populate orders data.

因此,如果可以使用MailDefinition类,那么请向我提供代码,该代码如何迭代循环并生成订单明细正文。

so if it is possible using MailDefinition class then please guide me with code that how can i iterate in loop and generate body for orders detail.

推荐答案

作为MailDefinition的替代方案,请查看RazorEngine https://github.com/Antaris/RazorEngine

As an alternative to MailDefinition, have a look at RazorEngine https://github.com/Antaris/RazorEngine.


RazorEngine是一个围绕
构建的简化模板框架Microsoft新的Razor解析引擎在ASP.NET MVC3和
网页中均使用。 RazorEngine提供了围绕解析引擎构建的包装器和其他服务
,以允许将
的解析技术用于其他项目类型

它使您可以在ASP.NET MVC之外使用剃刀模板,然后编写如下代码(未经测试):

It lets you use razor templates outside of ASP.NET MVC and then write something like this (not tested):

string template =
@"<html>
<body>
Hi @Model.FirstName @Model.LastName,

Here are your orders: 
@foreach(var order in Model.Orders) {
    Order ID @order.Id Quantity : @order.Qty <strong>@order.Price</strong>. 
}

</body>
</html>";

var model = new OrderModel {
    FirstName = "Martin",
    LastName = "Whatever",
    Orders = new [] {
        new Order { Id = 1, Qty = 5, Price = 29.99 },
        new Order { Id = 2, Qty = 1, Price = 9.99 }
    }
};

string mailBody = Razor.Parse(template, model);

这篇关于如何使用电子邮件模板发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆