Alex Rivera | Logout

Can I set up HTML/Email Templates with ASP.NET?

Asked 2009-03-06T20:21:10.830
100

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.

Edit
Report

2 Answers

1

I think the easy answer is MvcMailer. It s NuGet package that lets you use your favorite view engine to generate emails. See the NuGet package here and the project documentation

Hope it helps!

answered 2011-03-09T04:45:34.043
0

Here is a simple way using the WebClient class:

public static string GetHTMLBody(string url)
{
    string htmlBody;

    using (WebClient client = new WebClient ())
    {
        htmlBody = client.DownloadString(url);
    }

    return htmlBody;
}

Then just call it like this:

string url = "http://www.yourwebsite.com";
message.Body = GetHTMLBody(url);

Of course, your CSS will need to be in-lined in order to show the styles of the webpage in the most email clients (such as Outlook). If your e-mail displays dynamic content (ex. Customer Name), then I would recommend using QueryStrings on your website to populate the data. (ex. http://www.yourwebsite.com?CustomerName=Bob)

answered 2012-10-18T19:28:13.700

Your Answer