October 25, 2008 4

Send Templated Emails Using MailDefinition Object

By in Tags: ,

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 = "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);
}

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:

<%Address1%>,
<%Address2%>
<%City%>, <%State%> <%Zip%>

Thank You,
My Site

Tags: ,

4 Responses to “Send Templated Emails Using MailDefinition Object”

  1. Kuriyya says:

    Very useful information. I think it is useful for many people. Thank you for your blogs.

  2. Hi Jesal,
    Thanks for such an informative article on a very complex(as for as I am concerned) topic , But I couldn’t use background image in the mail as taking guidance from your article. Would you like to tell how will it be possible?

  3. thiago says:

    Thanks! your post help me very

  4. JB says:

    +1, the good example I was looking for, thx.

Leave a Reply