Monday, June 1, 2009

Sending Templated Emails Using MailDefinition Object

There is a better way to format your email messages in ASP.NET using the MailDefinition object. It lets you to use an email template and define tokens which you want to replace in it. This helps keep the presentation and business layers clean & seperate and lets the designers go in and edit the email templates without having to navigate the StringBuilder jungle.

private void SendEmail(int customerID)

{
 
Customer customer = CustomerData.GetCustomer(customerID);

 MailDefinition mailDefinition = new MailDefinition();

 mailDefinition.BodyFileName = "~/Email-Templates/Order-Confirmation.html";

 mailDefinition.From = "no-reply@my-site.com";

//Create a key-value collection of all the tokens you want to replace in your template...

  ListDictionary ldReplacements = new ListDictionary();

 ldReplacements.Add("<%FirstName%>", customer.FirstName);

 ldReplacements.Add("<%LastName%>", customer.LastName);

 ldReplacements.Add("<%Address1%>", customer.Address1);

 ldReplacements.Add("<%Address2%>", customer.Address2);

 ldReplacements.Add("<%City%>", customer.City);

 ldReplacements.Add("<%State%>", customer.State);

 ldReplacements.Add("<%Zip%>", customer.Zip);

 string mailTo = string.Format("{0} {1} <{2}>", customer.FirstName, customer.LastName, customer.EmailAddress);

MailMessage mailMessage = mailDefinition.CreateMailMessage(mailTo, ldReplacements, this);

mailMessage.From = new MailAddress("no-reply@my-site.com", "My Site");

mailMessage.IsBodyHtml = true;

mailMessage.Subject = "Order Confirmation";

SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["SMTPServer"].ToString(), 25);

smtpClient.Send(mailMessage);
}

Refrences:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.maildefinition.aspx