refer :

https://dotnetcoretutorials.com/2017/08/20/sending-email-net-core-2-0/

https://ppolyzos.com/2016/09/09/asp-net-core-render-view-to-string/

https://github.com/aspnet/Entropy/blob/dev/samples/Mvc.RenderViewToString/RazorViewToStringRenderer.cs ( 这个很干净, 没有依赖 http request )

直接看代码

要使用 Razor 模板需要提供这 2 个 服务

public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ICompositeViewEngine, CompositeViewEngine>();
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
}

Controller 注入相关服务

public class EmailController : Controller
{
public EmailController(
IOptionsSnapshot<Configuration.Email> emailOptionsAccessor,
ICompositeViewEngine compositeViewEngine,
IActionContextAccessor actionContextAccessor
)
{
emailConfig = emailOptionsAccessor.Value;
this.compositeViewEngine = compositeViewEngine;
actionContext = actionContextAccessor.ActionContext;
} private Configuration.Email emailConfig { get; set; }
private ICompositeViewEngine compositeViewEngine { get; set; }
private ActionContext actionContext { get; set; } }

最后呢

SmtpClient client = new SmtpClient
{
EnableSsl = emailConfig.enableSsl,
Port = emailConfig.port,
Host = emailConfig.host,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(emailConfig.username, emailConfig.password)
}; string body;
using (StringWriter sw = new StringWriter())
{
EmailTemplateViewmodel model = new EmailTemplateViewmodel
{
value = "dada"
};
ViewData.Model = model;
ViewEngineResult viewResult = compositeViewEngine.GetView(
null,
"~/Email/EmailTemplate.cshtml",
false
);
ViewContext viewContext = new ViewContext(actionContext, viewResult.View, ViewData, TempData, sw, new HtmlHelperOptions());
await viewResult.View.RenderAsync(viewContext);
body = sw.GetStringBuilder().ToString();
} MailMessage mailMessage = new MailMessage
{
From = new MailAddress(emailConfig.from, emailConfig.displayName),
Subject = "subject",
Body = body,
IsBodyHtml = true
};
mailMessage.To.Add("hengkeat87@gmail.com");
await client.SendMailAsync(mailMessage);

上面的依赖当前的请求

如果要不依赖请求的

注入

IServiceProvider serviceProvider,
ITempDataProvider tempDataProvider
private async Task<string> GenerateBodyFromTemplateAsync(string templatePath, object model)
{
string body;
using (StringWriter sw = new StringWriter())
{
// 这里渲染模板是不包含任何 http 请求的东西的, 所以模板里请不要使用 http 的东西哦
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = ServiceProvider;
var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
var viewData = new ViewDataDictionary(metadataProvider: new EmptyModelMetadataProvider(), modelState: new ModelStateDictionary());
viewData.Model = model;
var data = new TempDataDictionary(actionContext.HttpContext, TempDataProvider);
var viewResult = CompositeViewEngine.GetView(null, templatePath, false);
var viewContext = new ViewContext(actionContext, viewResult.View, viewData, data, sw, new HtmlHelperOptions());
await viewResult.View.RenderAsync(viewContext);
body = sw.GetStringBuilder().ToString();
}
return body;
}

Asp.net core 学习笔记 ( Smtp and Razor template 电子邮件和 Razor 模板 )的更多相关文章

  1. Asp.Net Core学习笔记:入门篇

    Asp.Net Core 学习 基于.Net Core 2.2版本的学习笔记. 常识 像Django那样自动检查代码更新,自动重载服务器(太方便了) dotnet watch run 托管设置 设置项 ...

  2. ASP.NET Core 学习笔记 第一篇 ASP.NET Core初探

    前言 因为工作原因博客断断续续更新,其实在很早以前就有想法做一套关于ASP.NET CORE整体学习度路线,整体来说国内的环境的.NET生态环境还是相对比较严峻的,但是干一行爱一行,还是希望更多人加入 ...

  3. Asp.net Core学习笔记

    之前记在github上的,现在搬运过来 变化还是很大的,感觉和Nodejs有点类似,比如中间件的使用 ,努力学习ing... 优点 不依赖IIS 开源和跨平台 中间件支持 性能优化 无所不在的依赖注入 ...

  4. ASP.NET Core 学习笔记 第三篇 依赖注入框架的使用

    前言 首先感谢小可爱门的支持,写了这个系列的第二篇后,得到了好多人的鼓励,也更加坚定我把这个系列写完的决心,也能更好的督促自己的学习,分享自己的学习成果.还记得上篇文章中最后提及到,假如服务越来越多怎 ...

  5. ASP.NET Core 学习笔记 第四篇 ASP.NET Core 中的配置

    前言 说道配置文件,基本大多数软件为了扩展性.灵活性都会涉及到配置文件,比如之前常见的app.config和web.config.然后再说.NET Core,很多都发生了变化.总体的来说技术在进步,新 ...

  6. ASP.NET Core 学习笔记 第五篇 ASP.NET Core 中的选项

    前言 还记得上一篇文章中所说的配置吗?本篇文章算是上一篇的延续吧.在 .NET Core 中读取配置文件大多数会为配置选项绑定一个POCO(Plain Old CLR Object)对象,并通过依赖注 ...

  7. Asp.net core 学习笔记 ( Data protection )

    参考 : http://www.cnblogs.com/xishuai/p/aspnet-5-identity-part-one.html http://cnblogs.com/xishuai/p/a ...

  8. Asp.net core 学习笔记 SignalR

    refer : https://kimsereyblog.blogspot.com/2018/07/signalr-with-asp-net-core.html https://github.com/ ...

  9. Asp.net core (学习笔记 路由和语言 route & language)

    https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-2.1 https://doc ...

随机推荐

  1. winfrom弹出窗口用timer控件控制倒计时20秒后关闭

    功能描述: 因为在程序退出时需要确认是否是误操作,所以加了密码输入的子窗体,子窗体在20秒内会自动关闭 代码如下: private int count; private void Form2_Load ...

  2. vue项目搭建步骤

    https://blog.csdn.net/echo008/article/details/77099058 https://blog.csdn.net/echo008/article/details ...

  3. iot-web增加apis-namespace组件

    1  文件夹复制 apis 2 增加 3 增加module

  4. 9个用来爬取网络站点的 Python 库

    上期入口:10个不到500行代码的超牛Python练手项目 1️⃣Scrapy 一个开源和协作框架,用于从网站中提取所需的数据. 以快速,简单,可扩展的方式. 官网:https://scrapy.or ...

  5. 问题: 揭秘Angualr2 书上问卷调查

    npm install 初夏下面问题: 0 info it worked if it ends with ok1 verbose cli [ '/home/linux_ubuntu164/tools/ ...

  6. 爬虫出现Forbidden by robots.txt(转载 https://blog.csdn.net/zzk1995/article/details/51628205)

    先说结论,关闭scrapy自带的ROBOTSTXT_OBEY功能,在setting找到这个变量,设置为False即可解决. 使用scrapy爬取淘宝页面的时候,在提交http请求时出现debug信息F ...

  7. 把ArrayList集合中的字符串内容写到文本文件中

    list列表数据导出到指定路径文本文档中 public  String getSDCardPath() { String sdCard = Environment.getExternalStorage ...

  8. javascript DOM 常用方法

    前端HTML+CSS+JS流程导图:https://www.processon.com/view/link/5ad1c2d0e4b0b74a6dd64f3c HTML+CSS+Javascript+j ...

  9. LinQ各种方式查询、组合查询、IQueryable集合类型

    1.模糊查询(包含) Repeater1.DataSource = con.car.Where(r =>r.name.Contains(s)).ToList(); 2.开头查询 Repeater ...

  10. python str find & index 联系

    [1]相同点 (1)功能:检测字符串中是否包含子字符串str (2)语法: [1] str.find(str, beg = 0, end = len(string)) [2] str.index(st ...