C# 我可以使用 ASP.NET 设置 HTML/电子邮件模板吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/620265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 10:33:58  来源:igfitidea点击:

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

c#asp.netemailtemplates

提问by John Bubriski

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.

如果我将 HTML 嵌入到 C# 字符串文字中,这很丑陋,他们将不得不担心转义。包括页眉和页脚的平面文件可能会起作用,但关于它的某些东西感觉不对。

What would be ideal what be to use a .ASPXpage as a template somehow, then just tell my code to serve that page, and use the HTML returned for the email.

什么是理想的以.ASPX某种方式使用页面作为模板,然后只需告诉我的代码为该页面提供服务,并使用为电子邮件返回的 HTML。

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!

更新:
我添加了一个答案,使您能够使用标准的 .aspx 页面作为电子邮件模板。只需像往常一样替换所有变量,使用数据绑定等。然后捕获页面的输出,瞧!你有你的 HTML 电子邮件!

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.


使用 CAVEAT更新!!!:我在某些 aspx 页面上使用 MailDefinition 类很好,但是在正在运行的服务器进程期间尝试使用此类时,它失败了。我相信这是因为 MailDefinition.CreateMailMessage() 方法需要一个有效的控件来引用,即使它并不总是做一些事情。正因为如此,我会推荐我使用 asx 页面的方法,或者使用 ascx 页面的 Mun 方法,这似乎更好一些。

采纳答案by Mike Barlow - BarDev

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

这里已经有很多答案,但我偶然发现了一篇关于如何将 Razor 与电子邮件模板结合使用的精彩文章。Razor 是使用 ASP.NET MVC 3 推送的,但使用 Razor 不需要 MVC。这是做电子邮件模板的非常巧妙的处理

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. "

正如文章指出的那样,“Razor 最好的地方在于,与它的前身(网络表单)不同,它不与网络环境绑定,我们可以轻松地将其托管在网络之外,并将其用作各种用途的模板引擎。”

Generating HTML emails with RazorEngine - Part 01 - Introduction

使用 RazorEngine 生成 HTML 电子邮件 - 第 1 部分 - 简介

Leveraging Razor Templates Outside of ASP.NET: They're Not Just for HTML Anymore!

在 ASP.NET 之外利用 Razor 模板:它们不再仅适用于 HTML!

Smarter email templates in ASP.NET with RazorEngine

使用 RazorEngine 在 ASP.NET 中更智能的电子邮件模板

Similar Stackoverflow QA

类似的 Stackoverflow QA

Templating using new RazorEngine API

使用新的 RazorEngine API 进行模板化

Using Razor without MVC

在没有 MVC 的情况下使用 Razor

Is it possible to use Razor View Engine outside asp.net

是否可以在 asp.net 之外使用 Razor View Engine

回答by Josh Mein

Sure you can create an html template and I would recommend also a text template. In the template you can just put [BODY] in the place where the body would be placed and then you can just read in the template and replace the body with the new content. You can send the email using .Nets Mail Class. You just have to loop through the sending of the email to all recipients after you create the email initially. Worked like a charm for me.

当然你可以创建一个 html 模板,我也会推荐一个文本模板。在模板中,您只需将 [BODY] 放在放置正文的位置,然后您就可以读取模板并将正文替换为新内容。您可以使用 .Nets 邮件类发送电子邮件。您只需在最初创建电子邮件后循环将电子邮件发送给所有收件人。对我来说就像一种魅力。

using System.Net.Mail;

// Email content
string HTMLTemplatePath = @"path";
string TextTemplatePath = @"path";
string HTMLBody = "";
string TextBody = "";

HTMLBody = File.ReadAllText(HTMLTemplatePath);
TextBody = File.ReadAllText(TextTemplatePath);

HTMLBody = HTMLBody.Replace(["[BODY]", content);
TextBody = HTMLBody.Replace(["[BODY]", content);

// Create email code
MailMessage m = new MailMessage();

m.From = new MailAddress("[email protected]", "display name");
m.To.Add("[email protected]");
m.Subject = "subject";

AlternateView plain = AlternateView.CreateAlternateViewFromString(_EmailBody + text, new System.Net.Mime.ContentType("text/plain"));
AlternateView html = AlternateView.CreateAlternateViewFromString(_EmailBody + body, new System.Net.Mime.ContentType("text/html"));
mail.AlternateViews.Add(plain);
mail.AlternateViews.Add(html);

SmtpClient smtp = new SmtpClient("server");
smtp.Send(m);

回答by John Rudy

If you are able to allow the ASPNET and associated users permission to read & write a file, you can easily use an HTML file with standard String.Format()placeholders ({0}, {1:C}, etc.) to accomplish this.

如果你能允许ASPNET和关联用户的权限读写文件,你可以方便地使用标准的HTML文件String.Format()占位符({0}{1:C},等)来实现这一目标。

Merely read in the file, as a string, using classes from the System.IOnamespace. Once you have that string, pass it as the first argument to String.Format(), and provide the parameters.

仅使用System.IO命名空间中的类将文件作为字符串读入。获得该字符串后,将其作为第一个参数传递给String.Format(),并提供参数。

Keep that string around, and use it as the body of the e-mail, and you're essentially done. We do this on dozens of (admittedly small) sites today, and have had no issues.

保留该字符串,并将其用作电子邮件的正文,您基本上就完成了。我们今天在数十个(不可否认的小)站点上执行此操作,并且没有出现任何问题。

I should note that this works best if (a) you're not sending zillions of e-mails at a time, (b) you're not personalizing each e-mail (otherwise you eat up a ton of strings) and (c) the HTML file itself is relatively small.

我应该注意到,如果 (a) 您不是一次发送数以百万计的电子邮件,(b) 您没有个性化每封电子邮件(否则您会吃掉大量字符串)和 (c) ) HTML 文件本身比较小。

回答by John Sheehan

You could try the MailDefinition class

你可以试试MailDefinition 类

回答by Canavar

If you want to pass parameters like user names, product names, ... etc. you can use open source template engine NVelocityto produce your final email / HTML's.

如果您想传递用户名、产品名称等参数,您可以使用开源模板引擎NVelocity来生成最终的电子邮件/HTML。

An example of NVelocity template (MailTemplate.vm) :

NVelocity 模板示例 ( MailTemplate.vm):

A sample email template by <b>$name</b>.
<br />

Foreach example :
<br />    
#foreach ($item in $itemList)

[Date: $item.Date] Name: $item.Name, Value: $itemValue.Value
<br /><br />

#end

Generating mail body by MailTemplate.vm in your application :

在您的应用程序中通过 MailTemplate.vm 生成邮件正文:

VelocityContext context = new VelocityContext();
context.Put("name", "ScarletGarden");
context.Put("itemList", itemList);

StringWriter writer = new StringWriter();

Velocity.MergeTemplate("MailTemplate.vm", context, writer);

string mailBody = writer.GetStringBuilder().ToString();

The result mail body is :

结果邮件正文是:

A sample email template by ScarletGarden.

Foreach example :

[Date: 12.02.2009] Name: Item 1, Value: 09

[Date: 21.02.2009] Name: Item 4, Value: 52

[Date: 01.03.2009] Name: Item 2, Value: 21

[Date: 23.03.2009] Name: Item 6, Value: 24

ScarletGarden 的示例电子邮件模板 。

Foreach 示例:

[日期:12.02.2009] 名称:项目 1,值:09

[日期:21.02.2009] 名称:项目 4,价值:52

[日期:01.03.2009] 名称:项目 2,值:21

[日期:23.03.2009] 名称:项目 6,价值:24

For editing the templates, maybe you can use FCKEditorand save your templates to files.

对于编辑模板,也许您可​​以使用FCKEditor并将您的模板保存到文件中。

回答by Mark Brackett

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.

以某种方式使用 .ASPX 页面作为模板是最理想的,然后只需告诉我的代码为该页面提供服务,并使用为电子邮件返回的 HTML。

You could easily just construct a WebRequest to hit an ASPX page and get the resultant HTML. With a little more work, you can probably get it done without the WebRequest. A PageParser and a Response.Filter would allow you to run the page and capture the output...though there may be some more elegant ways.

您可以轻松地构建一个 WebRequest 来访问 ASPX 页面并获得结果 HTML。再多做一点工作,您就可以在没有 WebRequest 的情况下完成它。PageParser 和 Response.Filter 将允许您运行页面并捕获输出......尽管可能有一些更优雅的方法。

回答by Mun

You might also want to try loading a control, and then rendering it to a string and setting that as the HTML Body:

您可能还想尝试加载一个控件,然后将其呈现为一个字符串并将其设置为 HTML 正文:

// 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 protected]", "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.

您的用户控件可以包含其他控件,例如页眉和页脚,还可以利用数据绑定等功能。

回答by Bob The Janitor

Set the set the Email Message IsBodyHtml = true

设置Email Message IsBodyHtml = true

Take your object that contains your email contents Serialize the object and use xml/xslt to generate the html content.

获取包含电子邮件内容的对象序列化对象并使用 xml/xslt 生成 html 内容。

If you want to do AlternateViews do the same thing that jmein only use a different xslt template to create the plain text content.

如果你想做 AlternateViews 做同样的事情,jmein 只使用不同的 xslt 模板来创建纯文本内容。

one of the major advantages to this is if you want to change your layout all you have to do update the xslt template.

这样做的主要优点之一是,如果您想更改布局,只需更新 xslt 模板即可。

回答by John Bubriski

I think you could also do something like this:

我认为你也可以这样做:

Create and .aspx page, and put this at the end of the OnLoad method, or call it manually.

创建和.aspx 页面,并将其放在OnLoad 方法的末尾,或者手动调用它。

    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    HtmlTextWriter htmlTW = new HtmlTextWriter(sw);
    this.Render(htmlTW);

I'm not sure if there are any potential issues with this, but it looks like it would work. This way, you could use a full featured .aspx page, instead of the MailDefinition class which only supports Text replacements.

我不确定这是否有任何潜在问题,但看起来它会起作用。这样,您就可以使用功能齐全的 .aspx 页面,而不是仅支持文本替换的 MailDefinition 类。

回答by Everton

If flexibility is one of your prerequisites, XSLT might be a good choice, which is completely supported by .NET framework and you would be able to even let the user edit those files. This article (http://www.aspfree.com/c/a/XML/XSL-Transformations-using-ASP-NET/) might be useful for a start (msdn has more info about it). As said by ScarletGarden NVelocity is another good choice but I do prefer XSLT for its " built-in" .NET framework support and platform agnostic.

如果灵活性是您的先决条件之一,XSLT 可能是一个不错的选择,它完全受 .NET 框架支持,您甚至可以让用户编辑这些文件。本文(http://www.aspfree.com/c/a/XML/XSL-Transformations-using-ASP-NET/)可能对开始有用(msdn 有更多相关信息)。正如 ScarletGarden 所说,NVelocity 是另一个不错的选择,但我更喜欢 XSLT,因为它的“内置”.NET 框架支持和平台无关。

回答by Raj

i had a similar requirement on 1 of the projects where you had to send huge number of emails each day, and the client wanted complete control over html templates for different types of emails.

我对其中一个项目有类似的要求,您必须每天发送大量电子邮件,并且客户希望完全控制不同类型电子邮件的 html 模板。

due to the large number of emails to be sent, performance was a primary concern.

由于要发送大量电子邮件,性能是首要考虑的问题。

what we came up with was static content in sql server where you save entire html template mark up (along with place holders, like [UserFirstName], [UserLastName] which are replaced with real data at run time) for different types of emails

我们想出的是 sql server 中的静态内容,您可以在其中为不同类型的电子邮件保存整个 html 模板标记(以及占位符,如 [UserFirstName]、[UserLastName],它们在运行时被替换为真实数据)

then we loaded this data in asp.net cache - so we dont read the html templates over and over again - but only when they are actually changed

然后我们将这些数据加载到 asp.net 缓存中 - 所以我们不会一遍又一遍地读取 html 模板 - 但只有在它们实际更改时

we gave the client a WYSIWYG editor to modify these templates via a admin web form. whenever updates were made, we reset asp.net cache.

我们为客户提供了一个 WYSIWYG 编辑器,以通过管理 Web 表单修改这些模板。每当进行更新时,我们都会重置 asp.net 缓存。

and then we had a seperate table for email logs - where every email to be sent was logged. this table had fields called emailType, emailSent and numberOfTries.

然后我们有一个单独的电子邮件日志表 - 每封要发送的电子邮件都被记录下来。该表具有名为 emailType、emailSent 和 numberOfTries 的字段。

we simply ran a job every 5 minutes for important email types (like new member sign up, forgot password) which need to be sent asap

我们只是每 5 分钟为需要尽快发送的重要电子邮件类型(例如新会员注册、忘记密码)运行一次作业

we ran another job every 15 minutes for less important email types (like promotion email, news email, etc)

我们每 15 分钟为不太重要的电子邮件类型(如促销电子邮件、新闻电子邮件等)运行另一项工作

this way you dont block your server sending non stop emails and you process mails in batch. once an email is sent you set the emailSent field to 1.

这样您就不会阻止您的服务器发送不间断的电子邮件,并且您可以批量处理邮件。发送电子邮件后,您将 emailSent 字段设置为 1。