Skip to content
Bruno Sonnino
Menu
  • Home
  • About
Menu

Sending parametrized HTML emails with C#

Posted on 28 May 2018

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);
 }
C#

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);
}
C#

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);
}
C#

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);
}
C#

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]}");
}
C#

And register it like this:

Helpers.Register("FullName", FullName);
C#

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#”

  1. Pingback: Debugging emails sent with C# – Bruno Sonnino

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • May 2025
  • December 2024
  • October 2024
  • August 2024
  • July 2024
  • June 2024
  • November 2023
  • October 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • June 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • July 2021
  • June 2021
  • May 2021
  • April 2021
  • March 2021
  • February 2021
  • January 2021
  • December 2020
  • October 2020
  • September 2020
  • April 2020
  • March 2020
  • January 2020
  • November 2019
  • September 2019
  • August 2019
  • July 2019
  • June 2019
  • April 2019
  • March 2019
  • February 2019
  • January 2019
  • December 2018
  • November 2018
  • October 2018
  • September 2018
  • August 2018
  • July 2018
  • June 2018
  • May 2018
  • November 2017
  • October 2017
  • September 2017
  • August 2017
  • June 2017
  • May 2017
  • March 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
  • October 2016
  • September 2016
  • August 2016
  • July 2016
  • June 2016
  • May 2016
  • April 2016
  • March 2016
  • February 2016
  • October 2015
  • August 2013
  • May 2013
  • February 2012
  • January 2012
  • April 2011
  • March 2011
  • December 2010
  • November 2009
  • June 2009
  • April 2009
  • March 2009
  • February 2009
  • January 2009
  • December 2008
  • November 2008
  • October 2008
  • July 2008
  • March 2008
  • February 2008
  • January 2008
  • December 2007
  • November 2007
  • October 2007
  • September 2007
  • August 2007
  • July 2007
  • Development
  • English
  • Português
  • Uncategorized
  • Windows

.NET AI Algorithms asp.NET Backup C# Debugging Delphi Dependency Injection Desktop Bridge Desktop icons Entity Framework JSON Linq Mef Minimal API MVVM NTFS Open Source OpenXML OzCode PowerShell Sensors Silverlight Source Code Generators sql server Surface Dial Testing Tools TypeScript UI Unit Testing UWP Visual Studio VS Code WCF WebView2 WinAppSDK Windows Windows 10 Windows Forms Windows Phone WPF XAML Zip

  • Entries RSS
  • Comments RSS
©2025 Bruno Sonnino | Design: Newspaperly WordPress Theme
Menu
  • Home
  • About