如何在ASP.NET Core中配置身份库的电子邮件发送?

4
在ASP.NET中,您可以在App_Start文件夹的IdentityConfig.cs中为身份验证配置电子邮件,如我在这里所述。但是,在ASP.NET Core Identity 现在是一个库,默认情况下不包括此IdentityConfig.cs文件。那么我该如何配置电子邮件发送,例如注册确认?
2个回答

10
根据https://medium.com/@MisterKevin_js/enabling-email-verification-in-asp-net-core-identity-ui-2-1-b87f028a97e0,ASP.NET Core 2 在很大程度上依赖于依赖注入。Identity Library的RegisterModel(以及其他依赖电子邮件的模型)具有以下字段:
private readonly IEmailSender _emailSender;

您只需使用Startup.cs的ConfigureServices方法注入由您自己实现的IEmailSender即可:

public void ConfigureServices(IServiceCollection services)
    {
        ...

        services.AddTransient<IEmailSender, EmailSender>();
    }

您可以在项目的 Services 文件夹中定义 EmailSender 类。以下是可能的实现方式:

enter image description here

using Microsoft.AspNetCore.Identity.UI.Services;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;

namespace YourProject.Services
{
    public class EmailSender : IEmailSender
    {
        public Task SendEmailAsync(string email, string subject, string htmlMessage)
        {
            SmtpClient client = new SmtpClient
            {
                Port = 587,
                Host = "smtp.gmail.com", //or another email sender provider
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential("your email sender", "password")
            };

            return client.SendMailAsync("your email sender", email, subject, htmlMessage);
        }
    }
}

1
我们需要实例化 SmtpClient 吗?还是推荐通过 DI 进行注入? - variable

2
您可以参考以下步骤使用SMTP发送电子邮件:
  1. Create a EmailSender class, and contains the following method:

     public interface IMyEmailSender
     {
         void SendEmail(string email, string subject, string HtmlMessage);
     }
    
     public class MyEmailSender : IMyEmailSender
     {
         public IConfiguration Configuration { get; }
         public MyEmailSender(IConfiguration configuration)
         {
             Configuration = configuration;
         } 
         public void SendEmail(string email, string subject, string HtmlMessage)
         {
             using (MailMessage mm = new MailMessage(Configuration["NetMail:sender"], email))
             {
                 mm.Subject = subject;
                 string body = HtmlMessage;
                 mm.Body = body;
                 mm.IsBodyHtml = true;
                 SmtpClient smtp = new SmtpClient();
                 smtp.Host = Configuration["NetMail:smtpHost"];
                 smtp.EnableSsl = true;
                 NetworkCredential NetworkCred = new NetworkCredential(Configuration["NetMail:sender"], Configuration["NetMail:senderpassword"]);
                 smtp.UseDefaultCredentials = false;
                 smtp.Credentials = NetworkCred;
                 smtp.Port = 587;
                 smtp.Send(mm);
             }
         } 
     }
    
  2. Store the SMTP configuration information in the appsettings.json

    "NetMail": { "smtpHost": "smtp.live.com", "sender": "sender email", "senderpassword": "Password" },

  3. Register the EmailSernder in the ConfigureServices method in Startup.cs file.

         services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
             .AddEntityFrameworkStores<ApplicationDbContext>();
    
         services.AddTransient<IMyEmailSender, MyEmailSender>();
    
  4. In the Register.cs file, after creating user, you could use UserManager to get the EmailConfirmationToken, and get the callbackurl, then, call the SendEmail() method to send email.

             var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };
             var result = await _userManager.CreateAsync(user, Input.Password);
             if (result.Succeeded)
             {
                 _logger.LogInformation("User created a new account with password.");
    
                 var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                 code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                 var callbackUrl = Url.Page(
                     "/Account/ConfirmEmail",
                     pageHandler: null,
                     values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                     protocol: Request.Scheme);
    
                     _myEmailSender.SendEmail(Input.Email, "Confirm your Email", 
                     $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
    
之后,您将收到一封类似以下内容的电子邮件:

enter image description here

点击链接后,将重定向到确认电子邮件页面,然后检查数据库,EmailConfirmed已更改为True

enter image description here

参考资料:ASP.NET Core中的帐户确认和密码恢复

1
我们需要实例化 SmtpClient 吗?还是推荐通过 DI 进行注入? - variable
我只想自定义发送的邮件内容。有没有更好的方法而不必更改整个邮件服务? - Dosihris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接