how to send email wth email template c#

Thomas picture Thomas · May 9, 2012 · Viewed 51.3k times · Source

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.

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 = "[email protected]";
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("[email protected]", 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.

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.

Answer

David Tischler picture David Tischler · May 9, 2012

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

RazorEngine is a simplified templating framework built around Microsoft's new Razor parsing engine, used in both ASP.NET MVC3 and Web Pages. RazorEngine provides a wrapper and additional services built around the parsing engine to allow the parsing technology to be used in other project types.

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