Generating HTML email body in C#

0 votes
asked May 20, 2009 by rob

Is there a better way to generate HTML email in C# (for sending via System.Net.Mail), than using a Stringbuilder to do the following:

string userName = "John Doe";
StringBuilder mailBody = new StringBuilder();
mailBody.AppendFormat("<h1>Heading Here</h1>");
mailBody.AppendFormat("Dear {0}," userName);
mailBody.AppendFormat("<br />");
mailBody.AppendFormat("<p>First part of the email body goes here</p>");

and so on, and so forth?

13 Answers

0 votes
answered Jan 20, 2009 by mark-dickinson

Emitting handbuilt html like this is probably the best way so long as the markup isn't too complicated. The stringbuilder only starts to pay you back in terms of efficiency after about three concatenations, so for really simple stuff string + string will do.

Other than that you can start to use the html controls (System.Web.UI.HtmlControls) and render them, that way you can sometimes inherit them and make your own clasess for complex conditional layout.

0 votes
answered Jan 20, 2009 by cyberzed

Well, it really depends on the solution as I see it. I have done everything from grabbing user-input and formatting it automaticly from different patters. The best solution I've done with html mails was actually xml+xslt formatting since we knew the input of the mail up-front.

0 votes
answered Jan 20, 2009 by richardod

That depends how complex your requirements are. I once had an application that rendered a table in an HTML email and I used an ASP.NET Gridview to render the HTML- concatenating strings to generate a table would have been messy.

0 votes
answered Jan 20, 2009 by leather

cyberzed - I have used a similar approach in the past (XML + XSLT) with good results too. This offers a lot of flexibility and means you code doesn't have to concern itself with the exact data this Email requires (Produce an XML doc containing all pertinent info and let the XSLT pick out the bit's it wants.

The only thing I would say is I found XSLT a bit of a headache to get into but I was fine once I got past the initial oddness.

0 votes
answered May 20, 2009 by anthonywjones

Use the System.Web.UI.HtmlTextWriter class.

StringWriter writer = new StringWriter();
HtmlTextWriter html = new HtmlTextWriter(writer);

html.WriteEncodedText("Heading Here");
html.WriteEncodedText(String.Format("Dear {0}", userName));
html.WriteEncodedText("First part of the email body goes here");

string htmlString = writer.ToString();

For extensive HTML that includes the creation of style attributes HtmlTextWriter is probably the best way to go. However it can be a bit clunky to use and some developers like the markup itself to be easily read but perversly HtmlTextWriter's choices with regard indentation is a bit wierd.

In this example you can also use XmlTextWriter quite effectively:-

writer = new StringWriter();
XmlTextWriter xml = new XmlTextWriter(writer);
xml.Formatting = Formatting.Indented;
xml.WriteElementString("h1", "Heading Here");
xml.WriteString(String.Format("Dear {0}", userName));
xml.WriteElementString("p", "First part of the email body goes here");
0 votes
answered May 20, 2009 by martinhn

You can use the MailDefinition class.

This is how you use it:

MailDefinition md = new MailDefinition();
md.From = "";
md.IsBodyHtml = true;
md.Subject = "Test of MailDefinition";

ListDictionary replacements = new ListDictionary();
replacements.Add("{name}", "Martin");
replacements.Add("{country}", "Denmark");

string body = "<div>Hello {name} You're from {country}.</div>";

MailMessage msg = md.CreateMailMessage("", replacements, body, new System.Web.UI.Control());

Also, I've written a blog post on how to generate HTML e-mail body in C# using templates using the MailDefinition class.

0 votes
answered May 20, 2009 by leather

I would recomend using templates of some sort. There are various different ways to approach this but essentially hold a template of the Email some where (on disk, in a database etc) and simply insert the key data (IE: Recipients name etc) into the template.

This is far more flexible because it means you can alter the template as required without having to alter your code. In my experience your likely to get requests for changes to the templates from end users. If you want to go the whole hog you could include a template editor.

0 votes
answered Jan 14, 2010 by david-clarke

There is similar StackOverflow question that contains some fairly comprehensive responses. Personally I use NVelocity as the template engine having previously tried using the ASP.Net engine to generate html email content. NVelocity is a lot simpler to use while still providing tons of flexibility. I found that using ASP.Net .aspx files for templates worked but had some unanticipated side effects.

0 votes
answered Jan 20, 2010 by simon-farrow

You might want to have a look at some of the template frameworks that are available at the moment. Some of them are spin offs as a result of MVC but that isn't required. Spark is a good one.

0 votes
answered Jan 15, 2012 by vladislav-zorov

If you don't want a dependency on the full .NET Framework, there's also a library that makes your code look like:

string userName = "John Doe";

var mailBody = new HTML {
    new H(1) {
        "Heading Here"
    new P {
        string.Format("Dear {0},", userName),
        new Br()
    new P {
        "First part of the email body goes here"

string htmlString = mailBody.Render();

It's open source, you can download it from

Disclaimer: I'm the author of this library, it was written to solve the same issue exactly - send an HTML email from an application.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter