Use the Razor view engine to generate mail content and razor mail content
The Mail content is actually HTML. The traditional method is to concatenate strings in the program to generate the mail content, which is difficult to generate and difficult to maintain. Razor is the view engine used in MVC to generate HTML. In ZKEACMS, the Razor view engine is used to generate mail content using cshtml as the mail template. This facilitates maintenance and modification.
Define the IViewRenderService
Two methods are defined in the interface. The first method is that ViewModel is not used in the view. You can directly input the view path. The second is that the view has a function ViewModel. You can pass in the view path and ViewModel object.
namespace Easy.Mvc.RazorPages{ public interface IViewRenderService { string Render(string viewPath); string Render<Model>(string viewPath, Model model); }}Interface implementation ViewRenderService
The implementation method is also relatively simple, and RazorViewEngine is used directly:
Namespace Easy. mvc. razorPages {public class ViewRenderService: IViewRenderService {private readonly container _ viewEngine; private readonly container _ prop; private readonly IServiceProvider _ serviceProvider; public ViewRenderService (Transport viewEngine, transport container, IServiceProvider serviceProvider) {_ viewEngine = viewEngine; _ tempDataPr Ovider = tempDataProvider; _ serviceProvider = serviceProvider;} public string Render (string viewPath) {return Render (viewPath, string. empty);} public string Render <TModel> (string viewPath, TModel model) {var httpContext = new DefaultHttpContext {RequestServices = _ serviceProvider}; var actionContext = new ActionContext (httpContext, new RouteData (), new ActionDescriptor (); var viewResult = _ ViewEngine. GetView (null, viewPath, false); if (! ViewResult. success) {throw new InvalidOperationException ($ "view template not found {viewPath}");} var viewDictionary = new ViewDataDictionary (new EmptyModelMetadataProvider (), new ModelStateDictionary ()) {Model = model}; using (var writer = new StringWriter () {var viewContext = new ViewContext (actionContext, viewResult. view, viewDictionary, new TempDataDictionary (actionContext. httpContext, _ tempDataProvider), writer, new HtmlHelperOptions (); var render = viewResult. view. renderAsync (viewContext); render. wait (); return writer. toString ();}}}}Use
The method is also very simple. First, you need to create a mail template, such as ResetPassword. cshtml
The Code is as follows:
@ Model ZKEACMS. Notification. ViewModels. ResetPasswordViewModel <! DOCTYPE html>
Next, call the ViewRenderService.
var htmlContent = _viewRenderService.Render("~/EmailTemplates/ResetPassword.cshtml", new ResetPasswordViewModel{Link=...});
With the content, you can directly call and send it.
Link: http://www.zkea.net/codesnippet/detail/post-62