Wednesday, August 11, 2010

Sending HTML Tempate based Email in Asp.Net

Few months ago one of our client requested a feature. They want to send HTML Template based email to their clients and staff containing some Dynamic data. I come up with following solution. I downloaded a open source parser vici.core. This is great tool and has lot of features HTML Template parser is just one on them.
First you should have HTML Template for the email. like
<blockquote>

<p>"

<strong>Creation Date:</strong>

$CreateDate

<strong>Order No:</strong>

$OrderNo

"</p>

</blockquote>
put a $ sign before your variables (that u want to provide on run time) in your html template. Then in your application add reference to vici.core. and use following code.
TemplateParser template = new TemplateParser();
IParserContext pContext = new CSharpContext();

Now in first value add name of your variable in html template. without $ sign

Dictionary emailData = new Dictionary();
emailData.Add("CreateDate", dpCDate.Text);
emailData.Add("OrderNo", txtOrderNo.Text);
emailData.Add("CDate", txtCompDate.Text);

foreach (KeyValuePair pair in eData)
{
pContext.Set(pair.Key, pair.Value);
}
string tempStr = File.ReadAllText("EmailTemplate.html");

MailMessage msg = new MailMessage();
msg.Subject = "Order Confirmation ";
msg.From = new MailAddress("from@yourdomain.com");
msg.Body = template.Render(tempStr, pContext);
msg.IsBodyHtml = true;

for (int i = 0; i < toAddrArray.Length; i++)
{
msg.To.Add(toAddrArray[i]);
}

///////////Define your smtp setting in web.config
var mailclient = new SmtpClient();
mailclient.Send(msg);


Hope this helps...


1 comment: