简体   繁体   English

Asp.Net Core Identity SendGrid 邮件未发送

[英]Asp.Net Core Identity SendGrid mails are not being sent

I am trying to find out why the account verification email is not being sent from my app when creating a new user account.我试图找出为什么在创建新用户帐户时没有从我的应用程序发送帐户验证 email。

I was able to send two emails on one of my first attempts.在我的第一次尝试中,我能够发送两封电子邮件。 The emails ended up in my spam filter, but they did get through.这些电子邮件最终进入了我的垃圾邮件过滤器,但它们确实通过了。 I do not know what may have changed since then.我不知道从那以后可能发生了什么变化。

Checking the SendGrid control panel, I can confirm that two emails was sent the first day I tried it, but none of my later attempts have generated any emails.检查 SendGrid 控制面板,我可以确认在我尝试的第一天发送了两封电子邮件,但我后来的尝试都没有生成任何电子邮件。

This article suggests to set a breakpoint on EmailSender.Execute . 本文建议在EmailSender.Execute上设置断点。 I have done that, and found that it is indeed not being hit.我这样做了,发现它确实没有被击中。 How do I debug further?如何进一步调试?

The SendGrid account information is specified in secrets.json: SendGrid 账户信息在 secrets.json 中指定:

{
  "SendGridUser": "{account name}",
  "SendGridKey": "{api-key}"
}

A service is configured in Startup.cs:在 Startup.cs 中配置了一个服务:

services.AddTransient<IEmailSender, EmailSender>();
services.Configure<AuthMessageSenderOptions>(Configuration);

AuthMessageSenderOptions: AuthMessageSender 选项:

public class AuthMessageSenderOptions
{
    public string SendGridUser { get; set; }
    public string SendGridKey { get; set; }
}

The EmailSender service: EmailSender 服务:

public class EmailSender : IEmailSender
{
    public EmailSender(IOptions<AuthMessageSenderOptions> optionsAccessor)
    {
        Options = optionsAccessor.Value;
    }

    public AuthMessageSenderOptions Options { get; } //set only via Secret Manager

    public Task SendEmailAsync(string email, string subject, string message)
    {
        return Execute(Options.SendGridKey, subject, message, email);
    }

    public Task Execute(string apiKey, string subject, string message, string email)
    {
        var client = new SendGridClient(apiKey);
        var msg = new SendGridMessage()
        {
            From = new EmailAddress("my@email.com", Options.SendGridUser),
            Subject = subject,
            PlainTextContent = message,
            HtmlContent = message
        };
        msg.AddTo(new EmailAddress(email));

        // Disable click tracking.
        // See https://sendgrid.com/docs/User_Guide/Settings/tracking.html
        msg.SetClickTracking(false, false);

        return client.SendEmailAsync(msg);
    }
}

A user is created like this:一个用户是这样创建的:

// user is an ApplicationUser-object
IdentityResult result = await userManager.CreateAsync(auto.Map<ApplicationUser>(user), "P&55w0rd");
if (result.Succeeded)
{
    ApplicationUser u = await userManager.FindByNameAsync(user.UserName);
    if (u != null)
    { 
        // newUser.RN is the role name to be assigned to the new user
        await userManager.AddToRoleAsync(u, newUser.RN);
    }
    return RedirectToAction("Details", new { id = user.Id });
}
else
{
    foreach (var error in result.Errors)
    {
        ModelState.AddModelError("", error.Description);
    }
}

A new user is created, added to the role and we are redirected to Users/Details/{id}, but the account verification email is not sent.创建了一个新用户,添加到该角色,我们被重定向到 Users/Details/{id},但没有发送帐户验证 email。

I'd be surprised if Identity does it by default, only by setting up the EmailSender.如果 Identity 在默认情况下仅通过设置 EmailSender 就可以做到这一点,我会感到惊讶。 You do not seem to provide any logic for the confirmation and nowhere to call the EmailSender.您似乎没有为确认提供任何逻辑,也无处可调用 EmailSender。

You need to inject the IEmailSender as a service in your controller where you are creating the user, and add the logic to generate a confirmation token and actually send the email.您需要在创建用户的IEmailSender作为服务注入,并添加生成确认令牌的逻辑并实际发送 email。

I'd expect something in the lines of:我期望以下内容:

var token = await userManager.GenerateEmailConfirmationTokenAsync(user);
var confirmationLink = Url.Action(nameof(ConfirmEmail), "Account", 
   new { token , email = user.Email }, 
   Request.Scheme);
await _emailSender.SendEmailAsync(user.Email, "Confirmation email link", confirmationLink);

Of course you could further look how to make your email prettier, but that's the core of it.当然,您可以进一步了解如何使您的 email 更漂亮,但这是它的核心。

Also, just to make sure that you have the whole picture, Identity does not also provide an email implementation by default, you also have to set it up: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/accconfirm?view=aspnetcore-3.1&tabs=visual-studio#install-sendgrid此外,为了确保您了解全貌,Identity 默认不提供 email 实现,您还必须对其进行设置: https://docs.microsoft.com/en-us/aspnet/core/安全/身份验证/accconfirm?view=aspnetcore-3.1&tabs=visual-studio#install-sendgrid

Sendgrid does not send the emails if the sender's email is not authenticated properly.如果发件人的 email 未正确验证,Sendgrid 不会发送电子邮件。 Hope this will be helpful for someone.希望这对某人有帮助。 Doc: https://app.sendgrid.com/settings/sender_auth文档: https://app.sendgrid.com/settings/sender_auth

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM