我可以使用 ASP.Net MVC Razor 视图生成格式良好的 HTML 正文作为从服务器发送的电子邮件的输入吗?

发布于 2024-10-21 12:09:53 字数 1153 浏览 3 评论 0原文

我想利用 Razor 视图的模型绑定/渲染功能为我从 ASP.NET MVC 应用程序发送的电子邮件生成 HTML 正文内容。

有没有办法将视图呈现为字符串,而不是将其作为 GET 请求的 ActionResult 返回?

为了说明这一点,我正在寻找能够执行以下操作的东西......

    public ActionResult SendEmail(int id)
    {
        EmailDetailsViewModel emailDetails = EmailDetailsViewModel().CreateEmailDetails(id);

        // THIS IS WHERE I NEED HELP...
        // I want to pass my ViewModel (emailDetails) to my View (EmailBodyRazorView) but instead of Rending that to the Response stream I want to capture the output and pass it to an email client.
        string htmlEmailBody = View("EmailBodyRazorView", emailDetails).ToString();

        // Once I have the htmlEmail body I'm good to go.  I've got a utilityt that will send the email for me.
        MyEmailUtility.SmtpSendEmail("[email protected]", "Email Subject", htmlEmailBody);

        // Redirect another Action that will return a page to the user confirming the email was sent.
        return RedirectToAction("ConfirmationEmailWasSent");
    }

I'd like to make use of the Model Binding / Rendering capabilities of a Razor View to generate the HTML Body Content for an email I'm sending from my ASP.NET MVC Application.

Is there a way to render a view to a string instead of returning it as the ActionResult of a GET request?

To illustrate I'm looking for something that will do the following...

    public ActionResult SendEmail(int id)
    {
        EmailDetailsViewModel emailDetails = EmailDetailsViewModel().CreateEmailDetails(id);

        // THIS IS WHERE I NEED HELP...
        // I want to pass my ViewModel (emailDetails) to my View (EmailBodyRazorView) but instead of Rending that to the Response stream I want to capture the output and pass it to an email client.
        string htmlEmailBody = View("EmailBodyRazorView", emailDetails).ToString();

        // Once I have the htmlEmail body I'm good to go.  I've got a utilityt that will send the email for me.
        MyEmailUtility.SmtpSendEmail("[email protected]", "Email Subject", htmlEmailBody);

        // Redirect another Action that will return a page to the user confirming the email was sent.
        return RedirectToAction("ConfirmationEmailWasSent");
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

○愚か者の日 2024-10-28 12:09:54

另一种是 ActionMailer.Net: https://bitbucket.org/swaj/actionmailer.net /wiki/Home

来自网站:Rails ActionMailer 库到 ASP.NET MVC 的基于 MVC 3 的端口。目标是使从应用程序发送电子邮件变得简单且相对轻松。

NuGet:安装包 ActionMailer

Another one would be ActionMailer.Net: https://bitbucket.org/swaj/actionmailer.net/wiki/Home

From the website: An MVC 3-based port of the Rails ActionMailer library to ASP.NET MVC. The goal is to make it easy and relatively painless to send email from your application.

NuGet: Install-Package ActionMailer

夜深人未静 2024-10-28 12:09:54

还有来自 NuGet 的 Essential Mail:Razor 软件包。它基于 RazorEngine 构建,并为电子邮件渲染提供简单的界面。

电子邮件消息模板看起来类似于

@inherits Essential.Templating.Razor.Email.EmailTemplate
@using System.Net;
@{
    From = new MailAddress("[email protected]");
    Subject = "Email Subject";
}
@section Html 
{
   <html>
      <head>
          <title>Example</title>
      </head>
      <body>
          <h1>HTML part of the email</h1>
      </body>
   </html>
}
@section Text 
{
    Text part of the email.
}

该项目托管在 GitHub 上: https: //github.com/smolyakoff/essential-templated/wiki/Email-Template-with-Razor

There is also Essential Mail: Razor package from NuGet. It is build over RazorEngine and provides simple interface for email rendering.

Email message template looks something like

@inherits Essential.Templating.Razor.Email.EmailTemplate
@using System.Net;
@{
    From = new MailAddress("[email protected]");
    Subject = "Email Subject";
}
@section Html 
{
   <html>
      <head>
          <title>Example</title>
      </head>
      <body>
          <h1>HTML part of the email</h1>
      </body>
   </html>
}
@section Text 
{
    Text part of the email.
}

The project is hosted on GitHub: https://github.com/smolyakoff/essential-templating/wiki/Email-Template-with-Razor

过气美图社 2024-10-28 12:09:54

根据 Ryan 的回答,我做了一个扩展方法:

public static string RenderViewToString(this Controller source, string viewName)
{
  var viewEngineResult = ViewEngines.Engines.FindView(source.ControllerContext, viewName, null);
  using (StringWriter output = new StringWriter())
  {
    viewEngineResult.View.Render(new ViewContext(source.ControllerContext, viewEngineResult.View, source.ViewData, source.TempData, output), output);
    viewEngineResult.ViewEngine.ReleaseView(source.ControllerContext, viewEngineResult.View);
    return output.ToString();
  }
}

从控制器操作内部调用(示例用法):

  [AllowAnonymous]
  public class ErrorController : Controller
  {
    // GET: Error
    public ActionResult Index(System.Net.HttpStatusCode id)
    {
      Exception ex = null; // how do i get the exception that was thrown?
      if (!Debugger.IsAttached)
        Code.Email.Send(ConfigurationManager.AppSettings["BugReportEmailAddress"], 
          $"Bug Report: AgentPortal: {ex?.Message}", 
          this.RenderViewToString("BugReport"));
      Response.StatusCode = (int)id;
      return View();
    }
  }

Based on Ryan's answer, I did an extension method:

public static string RenderViewToString(this Controller source, string viewName)
{
  var viewEngineResult = ViewEngines.Engines.FindView(source.ControllerContext, viewName, null);
  using (StringWriter output = new StringWriter())
  {
    viewEngineResult.View.Render(new ViewContext(source.ControllerContext, viewEngineResult.View, source.ViewData, source.TempData, output), output);
    viewEngineResult.ViewEngine.ReleaseView(source.ControllerContext, viewEngineResult.View);
    return output.ToString();
  }
}

To call from inside a controller action (example usage):

  [AllowAnonymous]
  public class ErrorController : Controller
  {
    // GET: Error
    public ActionResult Index(System.Net.HttpStatusCode id)
    {
      Exception ex = null; // how do i get the exception that was thrown?
      if (!Debugger.IsAttached)
        Code.Email.Send(ConfigurationManager.AppSettings["BugReportEmailAddress"], 
          $"Bug Report: AgentPortal: {ex?.Message}", 
          this.RenderViewToString("BugReport"));
      Response.StatusCode = (int)id;
      return View();
    }
  }
伏妖词 2024-10-28 12:09:54

仍在使用最后一个 MVC FullFW

http 的 Web 应用程序之外工作://fabiomaulo.blogspot.com/2011/08/parse-string-as-razor-template.html

您可以创建一个使用队列渲染并在网络外部发送电子邮件的工作线程。
代码行很少,您不需要 Razor 上的另一个包。

Still working outside a web app with the last MVC FullFW

http://fabiomaulo.blogspot.com/2011/08/parse-string-as-razor-template.html

You can create a worker consuming queue rendering and sending emails outside the web.
Few code lines, you don't need another package over Razor.

栩栩如生 2024-10-28 12:09:53

如果您只需要将视图呈现为字符串,请尝试如下操作:

public string ToHtml(string viewToRender, ViewDataDictionary viewData, ControllerContext controllerContext)
{
    var result = ViewEngines.Engines.FindView(controllerContext, viewToRender, null);

    using (var output = new StringWriter())
    {
        var viewContext = new ViewContext(controllerContext, result.View, viewData, controllerContext.Controller.TempData, output);
        result.View.Render(viewContext, output);
        result.ViewEngine.ReleaseView(controllerContext, result.View);

        return output.ToString();
    }
}

您需要从控制器操作中传入视图名称以及 ViewData 和 ControllerContext。

If you just need to render the view into a string try something like this:

public string ToHtml(string viewToRender, ViewDataDictionary viewData, ControllerContext controllerContext)
{
    var result = ViewEngines.Engines.FindView(controllerContext, viewToRender, null);

    using (var output = new StringWriter())
    {
        var viewContext = new ViewContext(controllerContext, result.View, viewData, controllerContext.Controller.TempData, output);
        result.View.Render(viewContext, output);
        result.ViewEngine.ReleaseView(controllerContext, result.View);

        return output.ToString();
    }
}

You'll need to pass in the name of the view and the ViewData and ControllerContext from your controller action.

指尖凝香 2024-10-28 12:09:53

您可以查看 Postal 以使用视图发送电子邮件。

You may checkout Postal for using views for sending emails.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文