You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core MVC中SendGrid无法发送注册确认邮件问题

ASP.NET Core MVC Identity注册确认邮件无法发送问题

我基于Scaffold Identity构建ASP.NET Core MVC应用,点击注册按钮后页面提示需检查邮箱完成确认,但确认邮件始终未送达。已配置好SendGrid密钥,且控制台应用测试SendGrid发信功能正常,但集成到项目后用户注册时邮件无法发送。

相关代码文件如下:

AuthMessageSenderOptions.cs

namespace aluguel.Services
{
    public class AuthMessageSenderOptions
    {
        public string? SendGridKey { get; set; }
    }
}

EmailSender.cs

using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.Extensions.Options;
using SendGrid;
using SendGrid.Helpers.Mail;

namespace aluguel.Services
{
    public class EmailSender : IEmailSender
    {
        private readonly ILogger _logger;

        public EmailSender(IOptions<AuthMessageSenderOptions> optionsAccessor,
                           ILogger<EmailSender> logger)
        {
            Options = optionsAccessor.Value;
            _logger = logger;
        }

        public AuthMessageSenderOptions Options { get; } //Set with Secret Manager.

        public async Task SendEmailAsync(string toEmail, string subject, string message)
        {
            if (string.IsNullOrEmpty(Options.SendGridKey))
            {
                throw new Exception("Null SendGridKey");
            }
            await Execute(Options.SendGridKey, subject, message, toEmail);
        }

        public async Task Execute(string apiKey, string subject, string message, string toEmail)
        {
            var client = new SendGridClient(apiKey);

            var msg = new SendGridMessage()
            {
                From = new EmailAddress("Joe@contoso.com", "Password Recovery"),
                Subject = subject,
                PlainTextContent = message,
                HtmlContent = message
            };
            msg.AddTo(new EmailAddress(toEmail));

            // Disable click tracking.
            msg.SetClickTracking(false, false);
            var response = await client.SendEmailAsync(msg);
            _logger.LogInformation(response.IsSuccessStatusCode
                                   ? $"Email to {toEmail} queued successfully!"
                                   : $"Failure Email to {toEmail}");
        }
    }
}

Program.cs

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.EntityFrameworkCore;
using aluguel.Areas.Identity.Data;
using aluguel.Services;

var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("ApplicationDbContextConnection") ?? throw new InvalidOperationException("Connection string 'ApplicationDbContextConnection' not found.");

builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString));

builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true).AddEntityFrameworkStores<ApplicationDbContext>();

builder.Services.AddTransient<IEmailSender, EmailSender>();

builder.Services.Configure<AuthMessageSenderOptions>(builder.Configuration);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.MapRazorPages();
app.Run();

排查及修复建议

  • 配置绑定校验:检查appsettings.json(或Secret Manager)中的SendGridKey节点位置。如果配置是放在"SendGrid": {"SendGridKey": "xxx"}这类子节点下,需将builder.Services.Configure<AuthMessageSenderOptions>(builder.Configuration);修改为builder.Services.Configure<AuthMessageSenderOptions>(builder.Configuration.GetSection("SendGrid"));,确保配置能正确绑定到AuthMessageSenderOptions。
  • 查看详细错误日志:在EmailSender的Execute方法中添加日志打印SendGrid的响应内容,比如:
    var responseBody = await response.Body.ReadAsStringAsync();
    _logger.LogInformation($"SendGrid Response: {responseBody}");
    
    以此获取具体错误原因,比如发件邮箱未验证、API权限不足、收件邮箱被拦截等。
  • 替换合法发件邮箱:代码中Joe@contoso.com是示例邮箱,必须替换为你在SendGrid控制台中验证过的发件邮箱,否则SendGrid会拒绝发送请求。
  • 异步调用检查:确认注册流程中调用SendEmailAsync时未使用.Wait()或.Result()等同步阻塞方法,避免异步任务未完成就终止请求。
  • 依赖注入顺序校验:确保AddDefaultIdentity与AddTransient<IEmailSender, EmailSender>的注册顺序正确,Identity框架会自动依赖注入IEmailSender实例完成邮件发送。

内容的提问来源于stack exchange,提问作者NÍCOLAS DINIZ DE CASTILHO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 21:52:50