I'm working on a site that will send out a significant number of emails. I want to set up both header and footer text, or maybe even templates to allow the users to easily edit these emails if they need to.
If I embed the HTML inside C# string literals, it's ugly and they would have to worry about escaping. Including flat files for the header and footer might work, but something about it just doesn't feel right.
What would be ideal what be to use a
.ASPX page as a template somehow, then just tell my code to serve that page, and use the HTML returned for the email.
Is there a nice and easy way to do this? Is there a better way to go about solving this problem?
I added an answer that enables you to use a standard .aspx page as the email template. Just replace all the variables like you normally would, use databinding, etc. Then just capture the output of the page, and voila! You have your HTML email!
UPDATED WITH CAVEAT!!!:
I was using the MailDefinition class on some aspx pages just fine, but when trying to use this class during a server process that was running, it failed. I believe it was because the MailDefinition.CreateMailMessage() method requires a valid control to reference, even though it doesn't always do something. Because of this, I would recommend my approach using an aspx page, or Mun's approach using an ascx page, which seems a little better.
There's a ton of answers already here, but I stumbled upon a great article about how to use Razor with email templating. Razor was pushed with ASP.NET MVC 3, but MVC is not required to use Razor. This is pretty slick processing of doing email templates
As the article identifies, "The best thing of Razor is that unlike its predecessor(webforms) it is not tied with the web environment, we can easily host it outside the web and use it as template engine for various purpose. "
Similar Stackoverflow QA
You might also want to try loading a control, and then rendering it to a string and setting that as the HTML Body:
// Declare stringbuilder to render control to StringBuilder sb = new StringBuilder(); // Load the control UserControl ctrl = (UserControl) LoadControl("~/Controls/UserControl.ascx"); // Do stuff with ctrl here // Render the control into the stringbuilder StringWriter sw = new StringWriter(sb); Html32TextWriter htw = new Html32TextWriter(sw); ctrl.RenderControl(htw); // Get full body text string body = sb.ToString();
You could then construct your email as usual:
MailMessage message = new MailMessage(); message.From = new MailAddress("email@example.com", "from name"); message.Subject = "Email Subject"; message.Body = body; message.BodyEncoding = Encoding.ASCII; message.IsBodyHtml = true; SmtpClient smtp = new SmtpClient("server"); smtp.Send(message);
You user control could contain other controls, such as a header and footer, and also take advantage of functionality such as data binding.