It’s a pretty common requirement these days to send a nicely formatted email, yet I’ve come across very few “nice” solutions.

The solution I’ve come to use is simple, and documented across the web, but rarely used in the real world.

The most common code I see (and what I used to write back in the days of .NET1.0 powered dinosaurs roaming the earth) revolves around ugly use of the StringBuilder:

MailBody.Append( "<html><head></head><body>

" ); MailBody.Append( "<span style=\"font-size: 11 px; font-family:Verdana,Helvetica, sans-serif\">Hi,<br><br>Your account information as it has been retrieved from the database:</span><br><br>

" ); MailBody.Append( "<div style=\"font-size: 11 px; font-family:Verdana,Helvetica, sans-serif\">Username: " + UserData.Username + "<br><br>" + "Password: " + UserData.Password + "</div>

" ); MailBody.Append( "</body></html>" );

Ugly. Unmaintainable.

Instead, create a user control for your email template using standard ASP.NET controls:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="PasswordRecovery.ascx.cs" Inherits="SampleApp.WebUI.EmailTemplates.PasswordRecovery" %> < h1 > Password Recovery </ h1 > < p > Your new password is < asp:Literal ID ="NewPassword" runat ="server" /> . </ p >

Expose a property for each value that you need to include in the email:

public string Password { get { return NewPassword.Text; } set { NewPassword.Text = value ; } }

Now just render the control on demand:

private string RenderControl(Control control) { StringBuilder stringBuilder = new StringBuilder(); StringWriter stringWriter = new StringWriter(stringBuilder); HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter); control.RenderControl(htmlTextWriter); return stringBuilder.ToString(); }

How simple is that. 🙂

UPDATE: I should mention how to instantiate the control – just calling the default constructor isn’t good enough as you’ll find that all of your controls are null. This is the magic line you’ll need:

EmailTemplates.MembershipApplication emailTemplate = (EmailTemplates.MembershipApplication)LoadControl( "~/EmailTemplates/MembershipApplication.ascx" );