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

在ASP.NET Core 7 WebAPI中使用SendGrid发送带HTML模板的4位数字OTP邮件

在ASP.NET Core 7 WebAPI中用SendGrid发送带OTP的HTML模板邮件

1. 先在SendGrid后台创建HTML模板

  • 登录SendGrid后台,进入「Email API」→「Dynamic Templates」,创建新模板
  • 添加一个版本,选择「Code Editor」,编写HTML模板,用占位符标记OTP位置,示例:
<!DOCTYPE html>
<html>
<head>
    <title>您的验证码</title>
    <style>
        .otp-code { color: #2563eb; font-size: 1.5rem; font-weight: bold; }
    </style>
</head>
<body>
    <div style="max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #eee;">
        <h3>您好!</h3>
        <p>请使用以下4位验证码完成验证:</p>
        <p class="otp-code">{{otp_code}}</p>
        <p>验证码5分钟内有效,请勿泄露给他人。</p>
    </div>
</body>
</html>
  • 保存模板后,记录下模板的Template ID,后续代码会用到

2. 配置ASP.NET Core项目

  • 在appsettings.json中添加SendGrid相关配置:
"SendGrid": {
  "ApiKey": "你的SendGrid API密钥",
  "TemplateId": "刚才记录的模板ID",
  "FromEmail": "your-app@example.com",
  "FromName": "你的应用名称"
}
  • 在Program.cs中注入SendGrid客户端:
builder.Services.AddSendGrid(options =>
{
    options.ApiKey = builder.Configuration["SendGrid:ApiKey"];
});

3. 编写OTP邮件发送服务

创建一个专用服务类,负责生成OTP并调用SendGrid发送模板邮件:

using SendGrid;
using SendGrid.Helpers.Mail;

public class OtpEmailService
{
    private readonly ISendGridClient _sendGridClient;
    private readonly IConfiguration _config;

    public OtpEmailService(ISendGridClient sendGridClient, IConfiguration config)
    {
        _sendGridClient = sendGridClient;
        _config = config;
    }

    // 生成4位随机OTP
    private string GenerateOtp()
    {
        var random = new Random();
        return random.Next(1000, 9999).ToString();
    }

    // 发送模板邮件
    public async Task<string> SendOtpAsync(string toEmail, string toName)
    {
        var otp = GenerateOtp();

        var message = new SendGridMessage
        {
            From = new EmailAddress(_config["SendGrid:FromEmail"], _config["SendGrid:FromName"]),
            Subject = "您的验证验证码"
        };
        message.AddTo(new EmailAddress(toEmail, toName));

        // 指定使用的SendGrid模板ID
        message.SetTemplateId(_config["SendGrid:TemplateId"]);

        // 传递模板变量,替换模板中的{{otp_code}}占位符
        message.AddTemplateData(new
        {
            otp_code = otp
        });

        // 发送邮件
        await _sendGridClient.SendEmailAsync(message);

        // 返回OTP,用于后续缓存验证(生产环境不要返回给前端)
        return otp;
    }
}

在Program.cs中注入这个服务:

builder.Services.AddScoped<OtpEmailService>();

4. 在控制器中调用服务

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/auth")]
public class AuthController : ControllerBase
{
    private readonly OtpEmailService _otpService;
    // 假设注入了缓存服务用于存储OTP
    private readonly IMemoryCache _cache;

    public AuthController(OtpEmailService otpService, IMemoryCache cache)
    {
        _otpService = otpService;
        _cache = cache;
    }

    [HttpPost("send-otp")]
    public async Task<IActionResult> SendOtp([FromBody] OtpRequest request)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var otp = await _otpService.SendOtpAsync(request.Email, request.Name);
        
        // 将OTP存入缓存,设置5分钟过期
        _cache.Set($"OTP_{request.Email}", otp, TimeSpan.FromMinutes(5));

        return Ok(new { Message = "验证码已发送至您的邮箱" });
    }
}

// 请求模型
public class OtpRequest
{
    [Required]
    [EmailAddress]
    public string Email { get; set; } = string.Empty;
    
    public string Name { get; set; } = string.Empty;
}

关键注意事项

  • 模板中的变量名必须和AddTemplateData传入的属性名完全匹配(区分大小写)
  • 确保SendGrid的API密钥具备发送权限,且发件人邮箱已完成验证
  • 生产环境中绝对不要将OTP返回给前端,仅存入缓存用于后续验证
  • 可根据需求扩展模板,比如添加品牌标识、自定义样式或更多动态内容

内容的提问来源于stack exchange,提问作者Professor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 10:54:55