13

他们是使用 ASP.NET MVC 视图生成电子邮件模板而无需跳过箍的解决方案。

让我详细说明一下跳跃。

var fakeContext = new HttpContext(HttpContext.Current.Request, fakeResponse);
var oldContext = HttpContext.Current;
HttpContext.Current = fakeContext;
var html = new HtmlHelper(new ViewContext(fakeControllerContext,
  new FakeView(), viewDataDictionary, new TempDataDictionary()),
  new ViewPage());
html.RenderPartial(viewName, viewData, viewDataDictionary);
HttpContext.Current = oldContext;

上面的代码是使用当前的 HttpContext 来伪造一个新的 Context 并使用 RenderPartial 渲染页面,我们不应该这样做。

另一个使用 ControllerContext 和 .Render 的非常详细的解决方案:(IEmailTemplateService, Headers/Postback WorkAround)但几乎用更多的代码做同样的事情。

另一方面,我正在寻找一种无需 POST/GET 即可呈现视图的东西,并为我生成一个简单的字符串,我可以通过我的电子邮件代码发送该字符串。不会遇到错误的东西,例如两次发布标题或伪造某些数据。

前任:

//code which does not fire Render, RenderPartial... etc
var email = emailFramework.Create(viewData, view); 

请参阅下面的解决方案或点击此链接:

我使用 spark 的解决方案:(12/30/2009) ASP.NET MVC 电子邮件模板解决方案

4

7 回答 7

11

这就是我希望 ASP.NET MVC ViewEngine 做的事情,但它在 Spark 中,只需点击下面的最新链接,

更新 (12/30/2009) Cleaner 版本: ASP.NET MVC 电子邮件模板解决方案


(11/16/2009)或者,Louis DeJardin 控制台应用程序版本:

using System;
using Spark;
using Spark.FileSystem;

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public abstract class EmailView : AbstractSparkView
{
    public User user { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        // following are one-time steps

        // create engine
        var settings = new SparkSettings()
            .SetPageBaseType(typeof(EmailView));

        var templates = new InMemoryViewFolder();
        var engine = new SparkViewEngine(settings)
                     {
                         ViewFolder = templates
                     };

        // add templates
        templates.Add("sample.spark", @"Dear ${user.Name}, This is an email.Sincerely, Spark View Engine http://constanto.org/unsubscribe/${user.Id}");

        // following are per-render steps

        // render template
        var descriptor = new SparkViewDescriptor()
            .AddTemplate("sample.spark");

        var view = (EmailView)engine.CreateInstance(descriptor);
        view.user = new User { Id = 655321, Name = "Alex" };
        view.RenderView(Console.Out);
        Console.ReadLine();
    }
}

我决定使用这种方法,因为它似乎是做所有事情的方法,它:

  • 不使用任何 HttpContext/ControllerContext 或弄乱路由数据!
  • 它可以实现页眉/页脚以允许模板!
  • 您可以使用循环、条件等...
  • 它干净,重量轻,特别是如果您打算完全转向火花视图引擎!

请务必阅读这些帖子。Louis DeJardin 的所有功劳参见他的教程 :): 使用 Spark 作为通用模板引擎!, 重新审视电子邮件模板

于 2009-11-13T23:17:59.450 回答
8

为什么需要从视图创建电子邮件?为什么不使用普通的旧模板文件?我一直这样做 - 我制作模板并使用来自城堡项目的 NVelocity 引擎(不要与 nvelocity VIEW 引擎混淆)来渲染模板。

例子:

var nvEngine = new NVelocityEngine();
nvEngine.Context.Add("FullName", fullName);
nvEngine.Context.Add("MallName", voucher.Mall.Name);
nvEngine.Context.Add("ConfirmationCode", voucher.ConfirmationCode);
nvEngine.Context.Add("BasePath", basePath);
nvEngine.Context.Add("TermsLink", termsLink);
nvEngine.Context.Add("LogoFilename", voucher.Mall.LogoFilename);

var htmlTemplate = System.IO.File.ReadAllText(
    Request.MapPath("~/App_Data/Templates/Voucher.html"));

var email = nvEngine.Render(htmlTemplate);

NVelocityEngine 类是我围绕 Castle 项目提供的 NVelocity 端口编写的包装器,如下所示:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NVelocity;
using NVelocity.App;

namespace MyProgram
{
    /// <summary>
    /// A wrapper for the NVelocity template processor
    /// </summary>
    public class NVelocityEngine : VelocityEngine
    {
        Hashtable context = new Hashtable();

        /// <summary>
        /// A list of values to be merged with the template
        /// </summary>
        public Hashtable Context
        {
            get { return context; }
        }

        /// <summary>
        /// Default constructor
        /// </summary>
        public NVelocityEngine()
        {
            base.Init();
        }

        /// <summary>
        /// Renders a template by merging it with the context items
        /// </summary>
        public string Render(string template)
        {
            VelocityContext nvContext;

            nvContext = new VelocityContext(context);
            using (StringWriter writer = new StringWriter())
            {
                this.Evaluate(nvContext, writer, "template", template);
                return writer.ToString();
            }
        }
    }
}

通过这种方式,您根本不必干预视图引擎,理论上您可以根据需要将其与 ASP.NET 视图引擎链接起来,就像我在以下控制器方法中所做的那样:

public ActionResult ViewVoucher(string e)
{
    e = e.Replace(' ', '+');
    var decryptedEmail = CryptoHelper.Decrypt(e);
    var voucher = Voucher.FindByEmail(decryptedEmail);
    if (voucher == null) return View("Error", new Exception("Voucher not found."));

    var basePath = new Uri(Request.Url, Url.Content("~/")).ToString();
    var termsLink = new Uri(Request.Url, Url.Action("TermsGC", "Legal")).ToString();
    basePath = basePath.Substring(0, basePath.Length - 1);

    var fullName = voucher.FirstName;
    if (!string.IsNullOrEmpty(voucher.LastName))
        fullName += " " + voucher.LastName;

    var nvEngine = new NVelocityEngine();
    nvEngine.Context.Add("FullName", fullName);
    nvEngine.Context.Add("MallName", voucher.Mall.Name);
    nvEngine.Context.Add("ConfirmationCode", voucher.ConfirmationCode);
    nvEngine.Context.Add("BasePath", basePath);
    nvEngine.Context.Add("TermsLink", termsLink);
    nvEngine.Context.Add("LogoFilename", voucher.Mall.LogoFilename);

    var htmlTemplate = System.IO.File.ReadAllText(
        Request.MapPath("~/App_Data/Templates/Voucher.html"));

    return Content(nvEngine.Render(htmlTemplate));
}
于 2009-11-13T19:45:49.363 回答
7

尝试使用火花视图引擎(http://www.sparkviewengine.com/)。它易于使用,比标准引擎更好,并且不需要伪造上下文。

您也可以使用此答案中的函数Render a view as a string,但它需要伪造上下文。这是标准视图引擎的工作方式,您对此无能为力。

这是我的扩展类,用于生成字符串视图。第一个是标准视图引擎,第二个是 Spark:

public static class ControllerHelper
{
    /// <summary>Renders a view to string.</summary>
    public static string RenderViewToString(this Controller controller,
                                            string viewName, object viewData)
    {
        //Getting current response
        var response = HttpContext.Current.Response;
        //Flushing
        response.Flush();

        //Finding rendered view
        var view = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName).View;
        //Creating view context
        var viewContext = new ViewContext(controller.ControllerContext, view,
                                          controller.ViewData, controller.TempData);

        //Since RenderView goes straight to HttpContext.Current, we have to filter and cut out our view
        var oldFilter = response.Filter;
        Stream filter = new MemoryStream(); ;
        try
        {
            response.Filter = filter;
            viewContext.View.Render(viewContext, null);
            response.Flush();
            filter.Position = 0;
            var reader = new StreamReader(filter, response.ContentEncoding);
            return reader.ReadToEnd();
        }
        finally
        {
            filter.Dispose();
            response.Filter = oldFilter;
        } 
    }

    /// <summary>Renders a view to string.</summary>
    public static string RenderSparkToString(this Controller controller,
                                            string viewName, object viewData)
    {
        var view = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName).View;
        //Creating view context
        var viewContext = new ViewContext(controller.ControllerContext, view,
                                          controller.ViewData, controller.TempData);

        var sb = new StringBuilder();
        var writer = new StringWriter(sb);

        viewContext.View.Render(viewContext, writer);
        writer.Flush();
        return sb.ToString();
    }
}
于 2009-11-13T16:24:28.557 回答
4

如果你想要简单的文本替换,.NET 有这样的东西:

        ListDictionary replacements = new ListDictionary();

        // Replace hard coded values with objects values
        replacements.Add("{USERNAME}", "NewUser");            
        replacements.Add("{SITE_URL}", "http://yourwebsite.com");
        replacements.Add("{SITE_NAME}", "My site's name");

        string FromEmail= "from@yourwebsite.com";
        string ToEmail = "newuser@gmail.com";

        //Create MailDefinition
        MailDefinition md = new MailDefinition();

        //specify the location of template
        md.BodyFileName = "~/Templates/Email/Welcome.txt";
        md.IsBodyHtml = true;
        md.From = FromEmail;
        md.Subject = "Welcome to youwebsite.com ";

        System.Web.UI.Control ctrl = new System.Web.UI.Control { ID = "IDontKnowWhyThisIsRequiredButItWorks" };

        MailMessage message = md.CreateMailMessage(ToEmail , replacements, ctrl);

        //Send the message
        SmtpClient client = new SmtpClient();

        client.Send(message);

和 Welcome.txt 文件

    Welcome - {SITE_NAME}<br />
    <br />
    Thank you for registering at {SITE_NAME}<br />
    <br />
    Your account is activated and ready to go! <br />
    To login, visit <a href="{SITE_URL}">{SITE_NAME}</a> and use the following credentials:
    <br />
    username: <b>{USERNAME}</b><br />
    password: use the password you registered with
    <br />
    <br />

    - {SITE_NAME} Team

同样,这仅适用于简单的字符串替换。如果您计划通过电子邮件发送更多数据,则需要正确格式化然后替换它。

于 2009-11-15T08:16:07.440 回答
3

您可以考虑使用 MvcMailer NuGet - 它完全符合您的要求,而且做得很干净。请参阅此处的 NuGet 包和项目文档

希望能帮助到你!

于 2011-03-09T04:34:48.657 回答
1

我为 LukLed 的 RenderSparkToString 方法创建了一个重载,它允许您在视图中使用 spark 布局:

public static string RenderSparkToString(this Controller controller,
                                        string viewName, string masterName, object viewData)
{
    var view = ViewEngines.Engines.FindView(controller.ControllerContext, viewName, masterName).View;
    //Creating view context
    var viewContext = new ViewContext(controller.ControllerContext, view,
                                      controller.ViewData, controller.TempData);

    var sb = new StringBuilder();
    var writer = new StringWriter(sb);

    viewContext.View.Render(viewContext, writer);
    writer.Flush();
    return sb.ToString();
}

不过,我同意安德鲁的观点。我希望有一种更简单的方法可以使用 Web 表单视图引擎来做到这一点。

于 2009-11-13T19:36:22.720 回答
0

虽然这是一个有点旧的线程,但如果你看一下 MvcMailer NuGet 包,我会鼓励你——它极大地简化了整个事情,并使邮件程序的行为更简单

于 2011-01-12T23:28:08.647 回答