为什么需要从视图创建电子邮件?为什么不使用普通的旧模板文件?我一直这样做 - 我制作模板并使用来自城堡项目的 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));
}