SendGrid发送邮件出现401 Unauthorized错误,求助原因排查
此前能够正常使用SendGrid发送邮件,但从昨日开始持续收到401 Unauthorized错误,使用的Node.js代码如下:
const sgMail = require('@sendgrid/mail') const aikey = 'SG.GCxxxxxxxxxxxxw.vMxxxxxxxxxvxxxxxxxxxxxM' sgMail.setApiKey(aikey) const msg = { to: 'test@example.com', // Change to your recipient from: 'test@example.com', // Change to your verified sender subject: 'Sending with SendGrid is Fun', text: 'and easy to do anywhere, even with Node.js', } sgMail .send(msg) .then((response) => { console.log(response[0].statusCode) console.log(response[0].headers) }) .catch((error) => { console.error(error) })
对应的错误信息如下:
ResponseError: Unauthorized at C:\Users\kennedy\Documents\try personalization\node_modules\@sendgrid\client\src\classes\client.js:146:29 at processTicksAndRejections (node:internal/process/task_queues:96:5) { code: 401, response: { headers: { server: 'nginx', date: 'Wed, 27 Jul 2022 08:22:58 GMT', 'content-type': 'application/json', 'content-length': '76', connection: 'close', 'access-control-allow-origin': 'https://sendgrid.api-docs.io', 'access-control-allow-methods': 'POST', 'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-of, x-sg-elas-acl', 'access-control-max-age': '600', 'x-no-cors-reason': 'https://sendgrid.com/docs/Classroom/Basics/API/cors.html', 'strict-transport-security': 'max-age=600; includeSubDomains' }, body: { errors: [Array] } } } [nodemon] clean exit - waiting for changes before restart
核心问题:当前使用的是SendGrid免费套餐,请问该错误是否由套餐类型导致?
解答
401 Unauthorized本质是身份验证失败,和免费套餐本身没有直接关联——免费套餐只会限制邮件发送量、高级功能权限,不会直接返回身份验证类错误。
优先排查以下几个方向:
- 确认API密钥正确性:检查代码中的密钥是否和SendGrid后台生成的完全一致,注意不要有多余空格、字符截断或修改。
- 检查密钥权限与状态:登录SendGrid后台,查看该API密钥是否被禁用、删除,或者是否拥有至少"Mail Send"的权限。
- 核实账户状态:确认免费账户是否因触发反垃圾规则、发送量超限未处理等原因被暂停,账户异常也可能导致身份验证环节失效。
- 排查网络环境:如果你的运行环境有代理设置,可能导致请求头中的Authorization字段被篡改,影响验证流程。
总结:先重点排查API密钥的有效性和正确性,这是401错误最常见的诱因,免费套餐本身不会直接引发该问题。
内容的提问来源于stack exchange,提问作者Kennedy Daniel
相关产品推荐
相关产品推荐

