Simple C# Email Template 'System'

Posted at 02:04 a.m. on 02/12/2010 by Daniel

As part of the new email system in Kustom Page, I decided to build a quick little template system, based off models, that could populate email fields, instead of doing a string.Format.

You pass it in a model (C# object), it runs through each of the properties, and applies them to the template file. Simple? Yes.

using System;
using System.Collections.Generic;
using System.Reflection;
using System.IO;

namespace KustomPage.Emailer.Client.TemplateEngine
{
    public class TemplateEngine<T>
    {
        private readonly T _templateModel;
        private readonly string _templateFilePath;

        public TemplateEngine(T templateModel, string templateFilePath)
        {
            _templateModel = templateModel;
            _templateFilePath = templateFilePath;
        }

        /// <summary>
        /// Renders the template.
        /// </summary>
        /// <returns></returns>
        public string Render()
        {
            IEnumerable<KeyValuePair<string, object>> modelProperties = GatherModelPropertiesAndValues();
            var output = LoadTemplate();

            foreach (var modelProperty in modelProperties)
            {
                output = output.Replace("<<" + modelProperty.Key + ">>", ObjectToString(modelProperty.Value));
            }

            return output;
        }

        /// <summary>
        /// Loads the template.
        /// </summary>
        /// <returns></returns>
        private string LoadTemplate()
        {
            return File.ReadAllText(_templateFilePath);
        }

        /// <summary>
        /// Converts the objects to a string.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        private static string ObjectToString(object value)
        {
            if (value == null)
                return string.Empty;

            if (value.GetType() == typeof(string))
                return (string)value;

            if(value.GetType() == typeof(DateTime))
            {
				// Add formatting here at some point
                DateTime dateTime = (DateTime)value;
                return dateTime.ToString();
            }

            return value.ToString();
        }

        /// <summary>
        /// Gathers the model properties and values into a dictionary
        /// </summary>
        /// <returns></returns>
        private IEnumerable<KeyValuePair<string, object>> GatherModelPropertiesAndValues()
        {
            IDictionary<string, object> properties = new Dictionary<string, object>();
            foreach (PropertyInfo propertyInfo in _templateModel.GetType().GetProperties())
            {
                string name = propertyInfo.Name;
                object value = propertyInfo.GetValue(_templateModel, null);

                properties.Add(name, value);
            }

            return properties;
        }
    }
}

Sample usage

Model

using System;
namespace KustomPage.Emailer.Client.Tests.TemplateEngine
{
    public class TemplateModel
    {
        public string Name { get { return "Daniel"; } }
        public string URL { get { return "http://www.kustompage.com/"; } }
        public DateTime Date { get; set; }
    }
}

And using it...

var model = new TemplateModel { Date = DateTime.Now };
TemplateEngine<TemplateModel> templateEngine = new TemplateEngine<TemplateModel>(model, "EmailTemplates/Test.txt");
var output = templateEngine.Render();

Sample template

Hello <<Name>>,


Pelase verify your account by clicking on the link below:

<<URL>>

This message was generated at <<Date>>

Post Comment
Name
Email Address
Website (Optional)
Comment
- Your comment will be moderated before it shows up.