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;
}

 

转载于:https://www.cnblogs.com/keatkeat/p/7576748.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值