Explain Codes LogoExplain Codes Logo

Generating HTML email body in C#

csharp
email-templates
maildefinition
razorengine
Alex KataevbyAlex Kataev·Jan 13, 2025
TLDR

Let's generate and dispatch an HTML-laden email using the mighty C#. You'll want to use StringBuilder for creating the HTML, and both MailMessage and SmtpClient to let the message loose:

var htmlBody = new StringBuilder("<html><body><h1>Your Subject</h1><p>Your message.</p></body></html>"); var message = new MailMessage("[email protected]", "[email protected]", "Subject", htmlBody.ToString()) { IsBodyHtml = true }; new SmtpClient("smtp.example.com").Send(message);

Substitute [email protected], [email protected], smtp.example.com, and the subject and message with your own data. This easy 1-2-3 creates a basic HTML email and sends it off across the internet, all with C#'s native email capabilities.

Advanced coding: HTML emails with MailDefinition

For crafting a more sophisticated email, turn to the MailDefinition class. MailDefinition empowers you to set your own From, Subject, and IsBodyHtml properties. This means you can structure every aspect of the headers and specify the body will carry our dear friend, HTML.

Envision making use of ListDictionary for dynamic content replacement:

var mailDef = new MailDefinition { From = "[email protected]", Subject = "Salutations!", IsBodyHtml = true }; // Prep a dictionary for replacements. No magic, promise! var replacements = new ListDictionary { { "<%Name%>", "John Doe" }, { "<%Country%>", "Everywhere" } // Spooky, he's everywhere! }; string body = "<html><body><p>Dear <%Name%>, welcome to <%Country%>. Enjoy!</p></body></html>"; var message = mailDef.CreateMailMessage("[email protected]", replacements, new Control()); // Message's ready! Let's shoot it off with SmtpClient like we did earlier. Go!

MailDefinition, our coder lifesaver!

By harnessing the MailDefinition class, you can create and send structured HTML without the need for clunky string concatenations. The CreateMailMessage generates your email body and follows a template-based approach for even easier modifications. Simply insert placeholders, and the method takes care of merging your template with your data.

Guides on how to implement MailDefinition with templates available online give much needed inspiration when crafting personalized emails or structuring rich HTML content.

Creation and personalization with templates

HTML templates act much like a blueprint in the astounding world of dynamic content creation. Define the base structure once, then simply fill placeholders much like you'd fill water into a bottle.

// templateString contains your HTML template var htmlBody = templateString.Replace("{UserName}", "Alice").Replace("{UserEmail}", "[email protected]");

Using RazorEngine for advanced templating

RazorEngine offers a potent way to tackle templating. It allows you to compile templates for repeated use and deal with complex conditional constructs. It's perfect when you need a high degree of flexibility in your templates:

string template = "Hello @Model.Name, welcome to @Model.Country!"; var model = new { Name = "John Doe", Country = "Wonderland" }; string result = Engine.Razor.RunCompile(template, "templateKey", null, model);

RazorEngine leverages C#'s dynamic features to parse templates using the razor syntax, providing impressive adaptability. This way, you can efficiently handle even complex email templates, like newsletters or transactional emails with many components.

Conclusion

Remember: every try takes you one step closer to becoming an expert. Each vote for my answer takes me one step closer to becoming famous! 😉
Happy coding! 👩‍💻