Templated E-Mail using .NET


One thing I’m pretty consistent about is letting the computer do most of my work for me.  As a “programmer” I really don’t like to program.  I prefer to solve problems.

You’ve already seen the effects of this in how I program PDF files where I use form fields and fill them at runtime rather than building up the entire PDF at runtime.

I use a similar technique when creating e-mails to send out from ASP.NET.

Here’s what I do

The first thing I do is to create an html file in my designer that looks just like what I want it to look like when the recipient receives it.

If you are planning to include images, you’ll want to make sure you include the base tag so that you can keep the images and the CSS on the server but build the page as though it lived on the web site instead of inside of a email client.  Otherwise, you’ll want to embed any CSS in your html file.

Within the document, you place “tags” that indicate where you want content from your program to go.  I normally use the format |tagName| where “tagName” is the name of the form field the content is coming from, if that is possible.  For example, if I had a form field I had named m_textBoxFirstName, my tag would be |m_textBoxFirstName|.  This makes my code easy to maintain in the future.

Once I’ve created my template, I just need a bit of code that will load the template and replace the variables.

StreamReader htmlStream = null;
htmlStream = new StreamReader(Server.MapPath("template.html"));
string htmlString = htmlStream.ReadToEnd();

// multiple replace lines
htmlString = htmlString.Replace("|m_textBoxFirstName|", m_textBoxFirstName.Text);

// send the email
SmtpClient smtp = new SmtpClient();
MailAddress from = new MailAddress(fromEmail, fromEmail);
MailAddress to = new MailAddress(emailAddress, emailAddress);
MailMessage message = MailMessage(from, to);
message.Subject = SubjectLine;
message.Body = htmlString;
message.IsBodyHtml = true;

Related Post

9 Responses to “Templated E-Mail using .NET”