Asp.net core 学习笔记 ( Smtp and Razor template 电子邮件和 Razor 模板 )
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 模板 )的更多相关文章
- Asp.Net Core学习笔记:入门篇
Asp.Net Core 学习 基于.Net Core 2.2版本的学习笔记. 常识 像Django那样自动检查代码更新,自动重载服务器(太方便了) dotnet watch run 托管设置 设置项 ...
- ASP.NET Core 学习笔记 第一篇 ASP.NET Core初探
前言 因为工作原因博客断断续续更新,其实在很早以前就有想法做一套关于ASP.NET CORE整体学习度路线,整体来说国内的环境的.NET生态环境还是相对比较严峻的,但是干一行爱一行,还是希望更多人加入 ...
- Asp.net Core学习笔记
之前记在github上的,现在搬运过来 变化还是很大的,感觉和Nodejs有点类似,比如中间件的使用 ,努力学习ing... 优点 不依赖IIS 开源和跨平台 中间件支持 性能优化 无所不在的依赖注入 ...
- ASP.NET Core 学习笔记 第三篇 依赖注入框架的使用
前言 首先感谢小可爱门的支持,写了这个系列的第二篇后,得到了好多人的鼓励,也更加坚定我把这个系列写完的决心,也能更好的督促自己的学习,分享自己的学习成果.还记得上篇文章中最后提及到,假如服务越来越多怎 ...
- ASP.NET Core 学习笔记 第四篇 ASP.NET Core 中的配置
前言 说道配置文件,基本大多数软件为了扩展性.灵活性都会涉及到配置文件,比如之前常见的app.config和web.config.然后再说.NET Core,很多都发生了变化.总体的来说技术在进步,新 ...
- ASP.NET Core 学习笔记 第五篇 ASP.NET Core 中的选项
前言 还记得上一篇文章中所说的配置吗?本篇文章算是上一篇的延续吧.在 .NET Core 中读取配置文件大多数会为配置选项绑定一个POCO(Plain Old CLR Object)对象,并通过依赖注 ...
- Asp.net core 学习笔记 ( Data protection )
参考 : http://www.cnblogs.com/xishuai/p/aspnet-5-identity-part-one.html http://cnblogs.com/xishuai/p/a ...
- Asp.net core 学习笔记 SignalR
refer : https://kimsereyblog.blogspot.com/2018/07/signalr-with-asp-net-core.html https://github.com/ ...
- Asp.net core (学习笔记 路由和语言 route & language)
https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-2.1 https://doc ...
随机推荐
- 清除 System.Web.Caching.Cache 以"xxx"开头的缓存
public static void ClearStartCache(string keyStart) { List<string> cacheKeys = new List<str ...
- 数组/Array/Tuple/yield
数组 如果需要使用同一类型的多个对象,就可以考虑使用集合和数组.如果需要使用不同类型的多个对象,可以考虑使用Tuple(元组) 数组的声明 在声明数组时,应先定义数组元素中的类型,其后是一对空方括号和 ...
- Mycat原理、应用场景
Mycat原理 Mycat的原理并不复杂,复杂的是代码,如果代码也不复杂,那么早就成为一个传说了.Mycat的原理中最重要的一个动词是“拦截”,它拦截了用户发送过来的SQL语句,首先对SQL语句做了一 ...
- vue.js 之 watch 详解
接我上篇博客的例子: 在上面代码中,当我们修改 firstName 或 lastName 后,watch 监听每次修改变化的新值,然后计算输出 fullName:此时 watch 的一个缺点是,最初绑 ...
- axios跨域请求报错
在nodejs的入口js中的配置路由之前加入这一段就可以了 app.all('*', function(req, res, next) { res.header("Access-Contro ...
- Redis入门到高可用(十三)—— 发布订阅
一.模型 二.主要API 1.publish(发布命令) 2.subcribe(订阅) 3.取消订阅(unsubcribe) 4.其他API 三.消息队列功能 redis实现消息队列功能 应用场景:抢 ...
- 墨刀联合有赞Vant组件库,让你轻松设计出电商原型
继上周新上线了简历模板之后,本周墨刀的原型模板库又欢喜地增添一名新成员! 有赞Vant组件库 (做电商的宝宝要捂嘴笑了) Vant 组件库是有赞前端团队开源的一套基于Vue的UI组件库,目前版本收 ...
- python常用函数及模块
原文来源于博客园和CSDN 1.计算函数 abs()--取绝对值 max()--取序列最大值,包括列表.元组 min()--取序列最小值 len()--取长度 divmod(a,b)---取a//b除 ...
- python类中的内置函数
__init__():__init__方法在类的一个对象被建立时,马上运行.这个方法可以用来对你的对象做一些你希望的初始化.注意,这个名称的开始和结尾都是双下划线.代码例子: #!/usr/bin/p ...
- 18 os/os.path模块中关于文件/目录常用的函数使用方法 (转)
os模块中关于文件/目录常用的函数使用方法 函数名 使用方法 getcwd() 返回当前工作目录 chdir(path) 改变工作目录 listdir(path='.') 列举指定目录中的文件名('. ...