【问题标题】:Asp.Net Core Identity SendGrid mails are not being sentAsp.Net Core Identity SendGrid 邮件未发送
【发布时间】:2020-06-09 04:28:18
【问题描述】:

我试图找出为什么在创建新用户帐户时没有从我的应用发送帐户验证电子邮件。

在我的第一次尝试中,我能够发送两封电子邮件。这些电子邮件最终进入了我的垃圾邮件过滤器,但它们确实通过了。我不知道从那以后可能发生了什么变化。

检查 SendGrid 控制面板,我可以确认在我尝试的第一天发送了两封电子邮件,但我以后的尝试都没有生成任何电子邮件。

This article 建议在EmailSender.Execute 上设置断点。我这样做了,发现它确实没有被击中。如何进一步调试?

SendGrid 账户信息在secrets.json 中指定:

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

在 Startup.cs 中配置了一个服务:

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

AuthMessageSenderOptions:

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

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

一个用户是这样创建的:

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

创建了一个新用户,添加到该角色,我们被重定向到用户/详细信息/{id},但未发送帐户验证电子邮件。

【问题讨论】:

  • 您包含的代码与发送电子邮件无关。请查看on-topic 指南:寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定问题或错误以及在问题本身中重现它所需的最短代码
  • @HoomanBahreini 我知道。我包含的代码显示了如何创建用户。电子邮件的发送由身份处理,我没有代码。
  • @HoomanBahreini 我在问题中添加了更多相关信息。我认为您可以取消投票以结束投票。

标签: c# sendgrid asp.net-core-identity


【解决方案1】:

如果发件人的电子邮件未正确验证,Sendgrid 不会发送电子邮件。 希望这对某人有帮助。 文档:https://app.sendgrid.com/settings/sender_auth

【讨论】:

    【解决方案2】:

    如果 Identity 在默认情况下仅通过设置 EmailSender 就可以做到这一点,我会感到惊讶。您似乎没有为确认提供任何逻辑,也无处可调用 EmailSender。

    您需要在创建用户的控制器中将IEmailSender 作为服务注入,并添加逻辑以生成确认令牌并实际发送电子邮件。

    我期待以下内容:

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

    当然,您可以进一步了解如何让您的电子邮件更漂亮,但这是它的核心。

    另外,为了确保您了解全貌,Identity 默认不提供电子邮件实现,您还必须设置它:https://docs.microsoft.com/en-us/aspnet/core/security/authentication/accconfirm?view=aspnetcore-3.1&tabs=visual-studio#install-sendgrid

    【讨论】:

    • 这对我来说有点像体力劳动。我的印象是 userManager 在创建用户和用户请求新密码时会为您发送电子邮件。这就是我阅读文档后的理解方式:docs.microsoft.com/en-us/aspnet/core/security/authentication/…
    • 我在问题中添加了 EmailSender 服务。我认为没有必要,因为它显示在我在问题中链接到的文档中,但它阐明了电子邮件的发送方式。
    • 我必须坚持。我浏览了 userManager.CreateAsync 的代码,没有可以自动发送任何电子邮件的代码路径。这需要默认做太多的假设。在注册操作期间正在模板中发送电子邮件:docs.microsoft.com/en-us/aspnet/core/security/authentication/…,它使用GenerateEmailConfirmationTokenAsync
    • 但我第一次尝试时如何成功发送两封电子邮件?正如我在问题中所说,我不知道自从我开始工作以来发生了什么变化。
    • 嘿...似乎以前有效(并且仍然有效)的电子邮件是用户单击链接以从/Identity/Account/Manage/Email向他们发送确认电子邮件的电子邮件,而不是在哪里在Users/Create 中创建了一个用户。
    猜你喜欢
    • 2023-04-04
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2017-06-05
    • 2021-11-19
    • 1970-01-01
    相关资源
    最近更新 更多