Sending emails in your app is a normal thing - after some operation, you must send confirmation data to the user, so he can keep the record of it. All the infrastructure for that is available in .NET, in the System.Net.Mail namespace, there is not much secret in that.
But sometimes things can be more difficult than that - there may be many templates for the email, depending on the kind of email you want to send, they are HTML based and the data in it must come from a different source, like a database.
Sending HTML emails
Sending an HTML email in .NET is fairly easy: you just have to create a MailMessage object, set its From, To, Subject and Body fields, set the IsBodyHtmlproperty to true and send the message using an SmtpClient object:
Templated emails
The previous code sends a fixed email, but sometimes we have to send a templated email, where we have a template and must fill it with some variables that come from a different source. The variable parts can come embedded in many ways, like between special characters, but I'll choose the Mustache (http://mustache.github.io/) way: using double braces before and after every variable, like this {{variable}}.
We now need to read the template, find the variables and replace them with the data, creating an HTML string that will be assigned to the Body property of the email:
As we are using a dictionary with the variables, I've added a new variable that doesn't come from the file: the current date. This method is very flexible and you can add data that comes from many sources.
The ProcessTemplate method uses a simple Regex replace to replace the found variables with the data in the dictionary:
Improving the processing
The processing we've chosen is very simple and we can improve it. We can use a library that processes the Mustache variables, like Nustache (https://github.com/jdiamond/Nustache). To use it, we just have to add the Nustache Nuget package. With it installed, the ProcessTemplate method becomes:
This is easier and doesn't rely in the Regex processing. You can also use some helper functions in the processing. For example, if your data file has the first and last name and you want the full name in the replaced template, you can define a function like this:
And register it like this:
Easy, no? Now we have a simple way to create a templated email with data coming from different sources. We've used Nustache to process the template, but you could use something else like Handlebars.net (https://github.com/rexm/Handlebars.Net), which would be very similar to what we did here.
The full source code for the project is in https://github.com/bsonnino/HtmlEmail
1 thought on “Sending parametrized HTML emails with C#”