使用 Razor 发送带有模板 MVC 的电子邮件

Sending emaills with template MVC using Razor

我想从我的站点发送一些邮件。

我创建了一个模板:OrderPlacedEmail.cshtml

@model OnlineCarStore.Models.PurchaseVM

<h1>Order Placed Email Notification</h1>
<p>@Model.Comments</p>

 Dear @Model.Name,

 <h2>Thank you.</h2>
<p>
You’ve made a purchase on <a href="">@Model.Comments</a>
</p>....and so on...

我创建了一个视图模型,我是这样使用它的:

 var template = Server.MapPath("~/Templates/OrderPlaced.cshtml");
 var viewModel = new PurchaseVM
 {
     GuId = new Guid(guidValue),
     Name = name,
     Address = address,
     Phone = phone,
     Email = email,
     Comments = comments,
     Date = DateTime.Now,
     CartList = cartList
 };

 var body = Razor.Parse(template, viewModel);

据我所知,Razor.Parse 方法应该用视图模型中的值替换模板中的所有细节。但是,正文获取模板位置的值,如下所示:

你能告诉我做错了什么吗?

If you wish there is a helper that i use

public static class HtmlOutputHelper
{

    public static string RenderViewToString(ControllerContext context,
                                string viewPath,
                                object model = null,
                                bool partial = false)
    {
        // first find the ViewEngine for this view
        ViewEngineResult viewEngineResult = null;
        if (partial)
            viewEngineResult = ViewEngines.Engines.FindPartialView(context, viewPath);
        else
            viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null);

        if (viewEngineResult == null)
            throw new FileNotFoundException("View cannot be found.");

        // get the view and attach the model to view data
        var view = viewEngineResult.View;
        context.Controller.ViewData.Model = model;

        string result = null;

        using (var sw = new StringWriter())
        {
            var ctx = new ViewContext(context, view,
                                        context.Controller.ViewData,
                                        context.Controller.TempData,
                                        sw);
            view.Render(ctx, sw);
            result = sw.ToString();
        }

        return result;
    }
}

On your controller

var viewModel = new PurchaseVM
 {
     GuId = new Guid(guidValue),
     Name = name,
     Address = address,
     Phone = phone,
     Email = email,
     Comments = comments,
     Date = DateTime.Now,
     CartList = cartList
 };

var emailTemplate = "~/Views/Templates/OrderPlaced.cshtml";
var emailOutput = HtmlOutputHelper.RenderViewToString(ControllerContext, emailTemplate, emailModel, false);

对于这种情况,您还可以使用 NuGet Gallery 中的 ActionMailerNext 库。

public class EmailController : MailerBase
{
//...
    public EmailResult OrderPlaced(Order order)
    {
        MailAttributes.To.Add(new MailAddress("to@email.com"));
        MailAttributes.From = new MailAddress("from@email.com");

        return Email("OrderPlaced", new PurchaseVM
        {
           //...
        });
    }
//...
}

您可以保持视图不变。