Email Templates in C#

Standard

For what must have been the zillionth time last weekend, I found myself writing code again for Y.A.T.E.S. (or, “Yet Another Template Email Sender”). I don’t know why I didn’t get around to adding some snippets into my library sooner, but I thought I’d share the following as I finally decided to write something which is a good starting point for future expansion.

Basically, it fetches any file from disk (you specify), reads the contents into a variable and then parses it for a list of tokens you supply, substituting the tokens with your own values. It works equally well with HTML and plain-text emails and supports multiple CC and BCC addresses.

EDIT: July 2011 – The project has now been updated to support fetching of template files from remote locations (by URL).

Usage

I’ve tried to keep it as simple and short as possible:

// Fetch template body from disk
var template = TemplateHelper.GetEmailTemplate("D:\Path\File.htm");

// Add any tokens you want to find/replace within your template file
var tokens = new Dictionary<string, string> {{"##FIRSTNAME##", "Richard"}, {"##LASTNAME##", "Parker"}};

// Specify addresses (CC and BCC are optional)
var to = new MailAddress("some_email_address@some_domain.com");
var fr = new MailAddress("some_email_sender@some_domain.com");

// Optionally, specify a List<MailAddress> for both CC and BCC fields, or pass null.
var cc = new List<MailAddress>() {new MailAddress("bar@foo.com"), new MailAddress("foo@bar.com")};
var bcc = new List<MailAddress>() {new MailAddress("fizz@buzz.com")};

// Send the mail
TemplateHelper.Send(to, fr, cc, bcc, "##FIRSTNAME##, thanks for registering!", tokens, template, true);

It’s free to use, you can use it as you wish, and it comes with all the usual disclaimers etc.

To get the source code, head on over to the CodePlex project at tokenmail.codeplex.com.

Enjoy!

Advertisements

2 thoughts on “Email Templates in C#

Comments are closed.