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:
static void Main(string[] args)
{
var mail = new MailMessage
{
From = new MailAddress("sender@gmail.com"),
Subject = "Test Mail",
Body = @" ... ",
IsBodyHtml = true
};
mail.To.Add("email@server.com");
var client = new SmtpClient("smtp.gmail.com")
{
Port = 587,
Credentials = new System.Net.NetworkCredential(
username, password),
EnableSsl = true
};
client.Send(mail);
}
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:
static void Main(string[] args)
{
var template = File.ReadAllText("EmailTemplate.html");
var data = JsonConvert.DeserializeObject<Dictionary>(
File.ReadAllText("EmailData.json"));
data.Add("date",DateTime.Now.ToShortDateString());
var emailBody = ProcessTemplate(template, data);
var mail = new MailMessage
{
From = new MailAddress("sender@gmail.com"),
Subject = "Test Mail",
Body = emailBody,
IsBodyHtml = true
};
mail.To.Add("email@server.com");
var client = new SmtpClient("smtp.gmail.com")
{
Port = 587,
Credentials = new System.Net.NetworkCredential(
username, password),
EnableSsl = true
};
client.Send(mail);
}
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:
private static string ProcessTemplate(string template,
Dictionary data)
{
return Regex.Replace(template, "\\{\\{(.*?)\\}\\}", m =>
m.Groups.Count > 1 && data.ContainsKey(m.Groups[1].Value) ?
data[m.Groups[1].Value] : m.Value);
}
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:
private static string ProcessTemplate(string template,
Dictionary data)
{
return Render.StringToString(template, data);
}
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:
private static void FullName(RenderContext context,
IList arguments, IDictionary options,
RenderBlock fn, RenderBlock inverse)
{
if (arguments?.Count >= 2)
context.Write($"{arguments[0]} {arguments[1]}");
}
And register it like this:
Helpers.Register("FullName", FullName);
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#”