Dynamic E-mail templates with Razor Engine
Until now all e-mails I had to send were quite simple, eg. "Thank you
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?