Can I set up HTML/Email Templates with ASP.NET?
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. "
Generating HTML emails with RazorEngine - Part 01 - Introduction
Leveraging Razor Templates Outside of ASP.NET: They’re Not Just for HTML Anymore!
Smarter email templates in ASP.NET with RazorEngine
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 toStringBuilder sb = new StringBuilder();// Load the controlUserControl ctrl = (UserControl) LoadControl("~/Controls/UserControl.ascx");// Do stuff with ctrl here// Render the control into the stringbuilderStringWriter sw = new StringWriter(sb);Html32TextWriter htw = new Html32TextWriter(sw);ctrl.RenderControl(htw);// Get full body textstring body = sb.ToString();
You could then construct your email as usual:
MailMessage message = new MailMessage();message.From = new MailAddress("from@email.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.