Asp.net core 学习笔记 ( Smtp and Razor template 电子邮件和 Razor 模板 )
2020-12-28
hotmail 和 gmail 参考 :
如果 send 的时候出现 error 比如类似 :
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated t
o send anonymous mail during MAIL FROM [SG2P153CA0043.APCP153.PROD.OUTLOOK.COM]
那多半是下面几个问题
gmail 一般上需要去 account bypass less secure apps, 有时候 bypass 了不可以可能是 cache 问题, 去 clear cache. 还是不可以的话可能需要搞 app password 之类的 (我没试过这个). 总之 gmail 超麻烦
hotmail 好一点,要确保 email active (binding contact number), 而且不可以有 two factory 设置.
还有就是 ssl 一定要 enable 咯, port 587, UseDefaultCredentials = false, TLS 1.2 或以上 (2022年 2 月 不支持 TLS 1.0, 1.1 了)
live.com 的 smtp 是 smtp.live.com (更新: 2022-05-21 smtp.live.com 已经废弃了, 改用 smtp.office365.com)
hotmail 的是 smtp.office365.com
gmail 的是 smtp.gmail.com
遇到 error 如果是 account 的问题, google 和微软是会发 email 告诉你的. 所以我们要确保 password 对, host, port 对.
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开发规范OWIN(3)—— Middleware
- Asp.Net_Mvc4_传值取值应用
- ASP.NET MVC加载ASCX之后,并为之赋值
- ASP.NET MVC获取上传的路径
- ASP.NET Core 1.0 Configuration 配置管理
- ASP.NET MVC搭建项目后台UI框架—9、服务器端排序
- ASP.NET MVC学习系列(一)-WebAPI初探
- C# ASP.NET发送电子邮件System.Net.Mail
- ASP.NET Core Library – CsvHelper
- Asp.net core 学习笔记 Fluent Validation
- ASP.NET Core MVC获取请求的参数方法示例
- ASP.NET Core MVC 如何获取请求的参数
- ASP.NET控件 > 传送带应用具体步骤
- ASP.NET Core中通过网站相对路径获取物理实际路径方法(Server.MapPath)
- ASP.NET Core ConfigureServices()中调用AddMvc()异常KeyNotFoundException
- ASP.NET Core中使用SmtpClient发送邮件的方法代码
- ASP.NET Core 2.1单元测试项目不能运行报错问题
- ASP.NET Core 后台方法中解析视图(View)获取生成的html字符串
- ASP.NET Core与ASP.NET区别
- 学习ASP.NET Core, 怎能不了解请求处理管道[3]: 自定义一个服务器感受一下管道是如何监听、接收和响应请求的
- 学习ASP.NET Core,怎能不了解请求处理管道[1]: 中间件究竟是个什么东西?
- ASP.NET Core的配置(2):配置模型详解
- 了解ASP.NET底层架构
- ASP.NET性能调试
- ASP.NET Core系列:中间件
- ASP.NET core webapi创建案例 _平台:windows (1)
- ASP.NET core webapi js请求 _平台:windows (6)
- 2019-8-31-ASP.NET-Core-开启后台任务
- ASP.NET Core开发-后台任务利器Hangfire使用