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?
Updated:
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.
The first and most important step to start with email templates is, One must use HTML tables to build the basic structure of an email template. Creating a table ensures that the content sent is not distorted on forwarding or mailing using different email applications.
No, bootstrap is not made for email templates.
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
Templating using new RazorEngine API
Using Razor without MVC
Is it possible to use Razor View Engine outside asp.net
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With