Send Templated Emails Using MailDefinition Object

Recently I discovered a better way to format my 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.

Here’s how its done.

private void SendEmail(long customerID)
	Customer customer = CustomerData.GetCustomer(customerID);

	MailDefinition mailDefinition = new MailDefinition();
	mailDefinition.BodyFileName = "~/Email-Templates/Order-Confirmation.html";
	mailDefinition.From = "[email protected]";

	//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("[email protected]", "My Site");
	mailMessage.IsBodyHtml = true;
	mailMessage.Subject = "Order Confirmation";

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

Your email template could be of any extension (txt, html, etc) as long as its in a text format. I personally like to keep it in HTML format so that we can preview the email template in a browser. Basically it’ll looks something like this -

Hello <%FirstName%> <%LastName%>,

Thank you for creating an account with us. Here are your details:

<%City%>, <%State%> <%Zip%>

Thank You,
My Site
If you have any questions or comments, please post them below. If you liked this post, you can share it with your followers or follow me on Twitter!