分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

使用MVC Razor生成格式良好的HTML Body作为邮件内容

发布时间:2023-09-06 01:46责任编辑:傅花花关键词:HTMLMVC邮件

PS: 实例化邮件类MailMessage有一个属性IsBodyHtml指示邮件正文是否是HTML格式。

我想利用Razor View的Model Binding / Rendering功能为我从ASP.NET MVC应用程序发送的电子邮件生成HTML Body Content。

有没有办法将视图呈现给字符串,而不是将其作为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("stevejobs@apple.com", "Email Subject", htmlEmailBody); ???????// Redirect another Action that will return a page to the user confirming the email was sent. ???????return RedirectToAction("ConfirmationEmailWasSent"); ???}

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

public string ToHtml(string viewToRender, ViewDataDictionary viewData, ControllerContext controllerContext){ ???var result = ViewEngines.Engines.FindView(controllerContext, viewToRender, null); ???StringWriter output; ???using (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。

可以Postal使用视图发送电子邮件:https://github.com/andrewdavey/postal

参考地址:https://cloud.tencent.com/developer/ask/61899

使用MVC Razor生成格式良好的HTML Body作为邮件内容

原文地址:https://www.cnblogs.com/riddly/p/8610183.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved