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

Blazor .NET 5 基于Identity实现带邮件确认的注册功能求助

.NET 5 Blazor Identity 邮件确认功能实现方案

核心实现步骤

    1. 定义邮件配置实体
      创建和配置字段匹配的实体类,用于绑定配置文件内容:
public class EmailConfiguration
{
    public string SmtpServer { get; set; }
    public int SmtpPort { get; set; }
    public string SmtpUsername { get; set; }
    public string SmtpPassword { get; set; }
}
    1. 绑定配置到依赖注入容器
      在Startup.cs的ConfigureServices方法中,添加配置绑定逻辑:
services.Configure<EmailConfiguration>(Configuration.GetSection("EmailConfiguration"));
    1. 实现Identity自带的邮件发送接口
      直接实现Microsoft.AspNetCore.Identity.UI.Services命名空间下的IEmailSender接口,无需自定义接口,Identity基架生成的注册逻辑会自动调用该服务:
using MailKit.Net.Smtp;
using MimeMessage = MimeKit.MimeMessage;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.Extensions.Options;

public class MailKitEmailSender : IEmailSender
{
    private readonly EmailConfiguration _emailConfig;
    public MailKitEmailSender(IOptions<EmailConfiguration> emailConfig)
    {
        _emailConfig = emailConfig.Value;
    }

    public async Task SendEmailAsync(string email, string subject, string htmlMessage)
    {
        var message = new MimeMessage();
        message.From.Add(new MimeKit.MailboxAddress("站点名称", _emailConfig.SmtpUsername));
        message.To.Add(new MimeKit.MailboxAddress("", email));
        message.Subject = subject;

        message.Body = new MimeKit.TextPart("html")
        {
            Text = htmlMessage
        };

        using var client = new SmtpClient();
        await client.ConnectAsync(_emailConfig.SmtpServer, _emailConfig.SmtpPort, true);
        client.AuthenticationMechanisms.Remove("XOAUTH2");
        await client.AuthenticateAsync(_emailConfig.SmtpUsername, _emailConfig.SmtpPassword);
        await client.SendAsync(message);
        await client.DisconnectAsync(true);
    }
}
    1. 注册邮件服务与Identity配置
      继续在ConfigureServices中添加以下逻辑,启用账号确认要求并注册邮件服务:
// 注册邮件发送服务
services.AddScoped<IEmailSender, MailKitEmailSender>();

// 配置Identity启用邮件确认
services.AddDefaultIdentity<IdentityUser>(options => 
    {
        options.SignIn.RequireConfirmedAccount = true;
    })
    .AddEntityFrameworkStores<ApplicationDbContext>();

Gmail SMTP 特殊配置说明

你当前使用的Gmail配置无法直接运行,需要额外调整账号设置:

  • 先为你的Google账号开启两步验证
  • 进入Google账号安全设置,创建应用专用密码,将配置中的SmtpPassword替换为生成的16位应用专用密码,不可直接使用账号登录密码
  • 如未开启两步验证,需开启「不太安全的应用访问权限」,但该方案已被Google逐步淘汰,不推荐使用

常见问题排查

  • 若465端口连接失败,可尝试将端口改为587,连接时第三个加密参数改为false,自动使用TLS加密
  • 确认运行环境的防火墙已开放对应SMTP端口的出站访问权限
  • 可在邮件发送逻辑中添加异常捕获,输出具体错误信息定位问题

内容的提问来源于stack exchange,提问作者Arkan I. Salman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 04:45:02