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

SendGrid邮件本地正常,部署至Azure App Service后返回空错误对象

Next.js + SendGrid 在Azure App Service部署后发送邮件返回空错误对象的排查与解决

1. 先修复错误日志,获取真实错误信息

当前返回空错误对象是因为SendGrid的Error对象在JSON序列化时丢失了关键信息,先修改API路由的错误处理逻辑,输出完整错误细节:

import type { NextApiRequest, NextApiResponse } from 'next'
import sgMail from '@sendgrid/mail'

sgMail.setApiKey(process.env.SEND_GRID_API_KEY)

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
    if(req.method == 'GET') {
        const msg = "This is a test message"

        try {
            await sgMail.send({
                to: process.env.SERVICES_INQUIRIES_EMAIL,
                from: process.env.SEND_GRID_VERIFIED_EMAIL,
                subject: "Test Email",
                html: msg
            })
            return res.status(200).json({'success': true})
        } catch (error: any) {
            // 输出详细错误到Azure日志(可在App Service日志面板查看)
            console.error('SendGrid Error:', {
                message: error.message,
                code: error.code,
                responseBody: error?.response?.body
            })
            // 返回结构化错误信息
            return res.status(500).json({
                success: false,
                error: {
                    message: error.message,
                    code: error.code,
                    details: error?.response?.body?.errors || []
                }
            })
        }
    }
}

export default handler

重新部署后调用接口,就能拿到具体错误原因(比如IP被SendGrid拦截、API Key权限不足、发件人未验证等)。

2. 排查Azure网络限制

  • 检查App Service的出站网络规则:确认允许访问https://api.sendgrid.com,如果开启了VNet集成或防火墙,需添加SendGrid的IP段到允许列表
  • 测试网络连通性:在App Service的Kudu控制台运行curl -v https://api.sendgrid.com/v3/mail/send,看是否能正常建立连接

3. 验证SendGrid配置

  • 确认API Key拥有发送邮件的权限(而非只读权限)
  • 检查SEND_GRID_VERIFIED_EMAIL是SendGrid后台已验证的发件人/域名,无违规标记
  • 登录SendGrid仪表盘,查看「邮件活动」面板,里面会记录每一封邮件的失败原因

4. 核对环境变量与Node版本

  • 在Azure App Service控制台执行echo $SEND_GRID_API_KEY,验证环境变量是否正确加载
  • 确保Azure上的Node.js版本与本地开发环境一致(在App Service「配置-常规设置」中调整)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 17:05:31