Dynamic E-mail templates with Razor Engine

Nemanja Malocic Categories: .net development Date 15-Jun-2014
Dynamic E Mail Templates With Razor Engine

Table of contents

    Until now all e-mails I had to send were quite simple, eg. "Thank you …" or "Your password has been changed to …" so string.replace has worked well for the purpose of making my e-mails dynamic. However, on the last project I was working on, we had to send an e-mail with all the messages a user has been receiving for the past X days and the e-mail had to be delivered in HTML format.

    The project was an MVC 3 project and it used Razor for views so I wondered if it's possible to use a similar "view & model" mechanism from our business layer as well for the purpose of building my dynamic e-mail template. After a little research I found that there is a wrapper around Razor engine that can be used for this purpose. It's a NuGet package which can be found at this address: https://www.nuget.org/packages/RazorEngine/ (or you can search for "RazorEngine" in Visual Studio's NuGet package manager). After I installed this NuGet package I had to write only a few lines of code and I was ready to go.

    Figure one shows our class that creates a string, which will be used as an e-mail body. First we read the entire content of the file that is written in Razor syntax. This file doesn't need .cshtml extension, it can be a simple .txt file, because Razor engine will parse it anyway. Model that you send to Razor.Parse() method is an object, so you need to be careful to send the correct model to the corresponding template.

    Figure two shows the part of the template that we have used to send notifications to our users. You can notice that there are repetition, flow control, etc. In this case we used .cshtml format for our template, so that we could take the advantage of IntelliSense when editing in VisualStudio.

    I like this approach because it's so easy to build and maintain dynamic HTML e-mail templates but also because the project is supported by Microsoft and will most likely be available and supported in the years to come.

    How do you like this approach to building dynamic e-mail templates and how do you implement dynamic e-mail templates in your .NET projects?

    Nemanja Malocic Software Developer

    Born to a family of lawyers, Nemanja knew from a young age that it was his destiny to leave the life of litigation for a life of the imagination.