Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Email Templates: A generic solution to handle template files

0.00/5 (No votes)
4 Nov 2004 1  
A simple, user-friendly and flexible framework that takes care of all your email template files - once and for all.

Introduction

Most web applications and quite a few desktop apps need to send emails from time to time: registration and activation mails, error warnings, confirmations etc. If not available through a database or CMS, the contents of these emails are mainly stored in text, HTML or XML files. I always considered this handling of template files to be a tedious task, so I came up with this solution that simplifies things remarkably.

Basically, this library handles the organization of arbitrary - optionally localized - template files for you. I really wanted to keep things simple and get a generic solution that does not rely on a database. As a result, you just have to create a single XML file that links to your templates to get things working.

Using the library at runtime is easy. To retrieve and send a localized template to a given recipient, you're done with three lines of code:

//get the template handler

TemplateHandler handler = TemplateHandler.Instance;

//get a french registration template

MailTemplate template = handler["registration", 
                        new CultureInfo("fr"];

//send the template 

handler.Send(template, "anybody@xxx.xxx");

Contents:

Setting up the XML file

All templates of your application are configured in a single XML file. You need to tell the framework where to find this file by adding the key Evolve.TemplateConfiguration to the appSettings section of your application configuration file (web.config / App.config). In web applications, you can use the tilde (~) to specify the virtual root of the application.

<appSettings>
  <add key="Evolve.TemplateConfiguration" 
          value="~/mailings/templates.config" />
</appSettings>

Here is a simple example of a configuration file. It contains the settings for two template groups:

  • Forum registrations: the email templates are available in English and German.
  • E-card notifications: no localization (only an English template).
<?xml version="1.0" encoding="utf-8" ?> 

<TemplateConfiguration>
  <BaseDirectory>template samples</BaseDirectory>
  <SmtpServer>mail.xxx.xxx</SmtpServer>

  <Groups>

    <!-- first group, localized templates -->
    <TemplateGroup TemplateGroupId="forumregistration"
      Sender="forums@xxx.xxx"
      MailFormat="Text">

      <Templates>

        <Template IsDefault="true">
          <Subject>your registration</Subject>
          <File>forum/registration_en.txt</File>
        </Template>

        <Template Locale="de">
          <Subject>Ihre Registrierung</Subject>
          <File>forum/registration_de.txt</File>
        </Template>
  
      </Templates>
     
    </TemplateGroup>

  
    <!-- second group, no localization -->
    <TemplateGroup TemplateGroupId="greetingcard"
      Sender="ecards@xxx.xxx"
      MailFormat="Html">

      <Templates>
         <Template IsDefault="true">
           <Subject>You got an eCard from {0}</Subject>
           <File>ecards/notification.txt</File>
         </Template>
      </Templates>
    </TemplateGroup>

  </Groups>

</TemplateConfiguration>

TemplateConfiguration element

This is the root element of the configuration file. It contains general settings that apply to all templates.

BaseDirectory Optional but recommended. If set, relative file paths of templates will be determined based on this folder. For web applications, you can use the tilde (~) to specify the virtual root.
SmtpServer Optional but recommended. The SMTP server which should be used to send out the messages.
Groups Contains one or more TemplateGroup declarations.

TemplateGroup element

As you can see, a configuration file contains several TemplateGroup elements. Every template group needs to have a unique ID which is used to request a given template.

TemplateGroupId Unique ID of the group which is used to request templates from the TemplateHandler controller class at runtime.
Sender The sender address used for emails.
MailFormat The format of the mail which can be either Text or Html.
File The path of the template file. May be absolute or relative.
Templates Contains one or more Template declarations.

Template element

Every template group contains a Templates listing with one or more Template elements in it. All templates of a given group contain messages for the same process (e.g., a registration confirmation) but in different languages.

Locale Defines the language of the template. Examples: en (English), de (German), de-ch (German [Switzerland]), fr-ch (French [Switzerland]). At runtime, you're dealing with corresponding CultureInfo objects.
IsDefault If set to true, this template is returned if a template for an unknown CultureInfo is being requested at runtime. In this case, the Locale attribute is not needed.
Subject The subject of the mail if the template is being sent via the TemplateHandler.
File The path of the template file. May be absolute or relative.

Working with the code

MailTemplate

A MailTemplate object encapsulates all settings of a template.

TemplateGroupId The group ID as defined in the TemplateGroup element of the XML file.
Locale The localization information of the template. On the default template of a template group, this is CultureInfo.InvariantCulture.
Subject The subject of the mail according to the configuration file.
Body The text that was stored in the template file.

You can easily adjust and format the contents of your MailTemplate objects. Every time you request a MailTemplate from the TemplateHandler, a new instance is being created. For details on formatting content, see Formatting your content.

TemplateHandler

The TemplateHandler controller class gives you access to specific templates by providing two indexers. They take a TemplateGroupId and an optional CultureInfo parameter for localization purpose. Once you have referenced a MailTemplate object, you can process it in your code and eventually send it to one or more recipients using one of the Send overloads.

TemplateHandler handler = TemplateHander.Instance;

//get the default template of the above sample

MailTemplate template1 = handler["forumregistration"];

//get the german template

MailTemplate template2 = handler["forumregistration", 
                         new CultureInfo("de")];

//this returns also the default template, as there is no french template:

MailTemplate template3 = handler["forumregistration", 
                         new CultureInfo("fr")];

//send the template

handler.Send(template3, "info@xxx.xxx");

Hook into the sending process

While just sending a mail through the TemplateHandler may be adequate in most situations, you might want to have more control in some situations. One solution is to create and send the email messages on your own. Another way is to work with the Send overloads that take a delegate of type TemplateCallbackHandler:

public delegate void TemplateCallbackHandler(MailTemplate template, 
                              MailMessage message);

If you use this feature, a callback handler is called by the framework before the MailMessage is sent to the recipients. This gives you full control over the email. The sample below uses the callback to attach a PDF file to the message before it's being sent to the recipient:

private void Send(MailTemplate template)
{
  TemplateHandler handler = TemplateHandler.Instance;

  //create delegate  

  TemplateCallbackHandler cb;
  cb = new TemplateCallbackHandler(HandleMessageCallback));

  //send message

  handler.Send(template, "info@xxx.xx", cb);
}



//this is the callback handler

private void HandleMessageCallback(MailTemplate template, 
                                          MailMessage message)
{
  //add file

  MailAttachment att = new MailAttachment("terms.pdf");
  message.Attachments.Add(att);
}

Formatting your content

Most of your templates will consist of dynamic parts: you need to include IDs and passwords, email addresses etc. The framework makes no assumptions about this. Let's say you need to format the subject of an email. In this sample, I just included the format placeholder {0}:

<Template IsDefault="true">
  <Subject>You got an eCard from {0}</Subject>
  <File>ecards/notification.txt</File>
</Template>

To adjust the subject, my code would look like this:

MailTemplate template = handler["greetingcard"];
template.Subject = String.Format(template.Subject, "Mr. Tarantino");

handler.Send(template, "info@xxxx.xx");

This would result in a mail with the following subject: You got an eCard from Mr. Tarantino.

The PropertyMapper helper class

However, I've built a simple helper class that automates the assignment of values to placeholders for you. There's no need to use it but it can come handy. The simple idea behind the PropertyMapper class is that you format your template with keys surrounded by special tags:

Example:

Hello #?FirstName?#
Your email address is #?EmailAddress?#

Now, let's assume you have a User class that provides properties that match these keys:

What you can do now is feed a User class and a MailTemplate to the PropertyMapper. It will replace all keys that match public properties of the User class with the corresponding property values: #?FirstName?# gets replaced by the value of the FirstName property, #?EmailAddress?# gets the value of the EmailAddress property, and so on. The code looks like this:

//get a user class

User user = new User(123);

//get a mail template

MailTemplate template = GetUserTemplate();

//create a mapper class with the User instance

PropertyMapper mapper = new PropertyMapper(user);

//map the object properties to the template

mapper.MapTemplate(template);

A few remarks:

  • Note that the opening tags (#?) and the closing tags (?#) are not the same!.
  • If the template contains keys that match no properties, they will not be changed. If you want to replace keys with properties of two different objects, you can easily exchange the objects and call MapTemplate a second time.
  • MapTemplate replaces keys in both Subject and Body of the template.
  • If a property value is null, the key will be replaced by an empty string.
  • You can also submit a string rather than a MailTemplate object by calling MapContent. The submitted string will not be changed but a new string returned.

MailTemplate lifecycle

The diagram below shows all processes from the retrieval of a template to its transmission:

Points of interest

I haven't covered the internals of the framework in this article. However, in case you want to know how things work, the code is well documented and should be easy to understand. Some points of interest:

  • The configuration file is being parsed using .NET's built-in XML deserialisation (using the XmlSerializer class). I love XML serialization as it makes things so easy! The Evolve.Util.MailTemplates.Xml namespace contains classes that match the elements of the configuration file.
  • The PropertyMapper class uses a Regular Expression to retrieve the placeholders of templates. Of course, there is Reflection involved to access the properties of submitted objects.

The ZIP file contains the source, a sample (WinForms-) application that works upon different templates, and a few NUnit tests.

Newsletter

This is the first release of the library, so there will probably be some enhancements / fixes. If you're using the library, I recommend to check back here from time to time. If you prefer to keep notified, you can subscribe to the corresponding newsletter on my site: Newsletter subscription.

Conclusion

This is a handy little library which can make your life a bit simpler if you're working with file-based templates. It's dead simple - and that's exactly what it needs to be. Enjoy :-).

History

  • 1.0.0: Nov. 3, 2004.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here