SendGrid出现HTTP 401 Unauthorized错误的技术求助
以下是针对你遇到问题的具体排查方向和解决方案:
一、先获取详细错误信息
当前代码仅打印异常对象e,无法获取SendGrid返回的具体错误原因(比如权限不足、发件人未验证等)。修改异常捕获逻辑,打印完整错误详情:
except Exception as e: print(f"错误详情: {e}") if hasattr(e, 'body'): print(f"错误响应体: {e.body}") return False
根据返回的具体提示,能更快定位核心问题。
二、排查API密钥权限
即使你换了新密钥,也要确认:
- 登录SendGrid后台,进入API Keys页面,查看当前使用的密钥是否勾选了Mail Send权限(这是发送邮件必须的权限,新生成密钥默认可能未开启全权限)。
三、验证发件人邮箱状态
SendGrid要求发件人邮箱必须经过官方验证,否则会触发权限拦截:
- 进入SendGrid的Sender Authentication页面,确认
fromemail@id这个邮箱处于已验证状态:- 若为单发件人验证:检查邮箱是否被取消验证、是否存在拼写错误;
- 若为域名验证:检查域名的DNS记录(SPF、DKIM、DMARC)是否正常生效,未过期。
四、适配SendGrid库版本与调用方式
你的代码使用sg.client.mail.send.post(request_body=mail_json)的调用方式,可能因库版本更新出现兼容性问题:
- 运行
pip show sendgrid查看当前版本,新版SendGrid推荐直接使用sg.send(mail)方法,无需手动转换JSON:
# 替换原response = sg.client.mail.send.post(...) 这一行 response = sg.send(mail)
五、检查收件人参数格式
代码中from_email使用了To对象,但调用时to_email直接传字符串,可能导致请求格式不合法:
- 要么在调用时包装成
To对象:
send_mail_utils.send_mail(To('toemail'), 'testing', 'This is the message')
- 要么在函数内部自动处理字符串转
To对象:
def send_mail(to_email, subject, message, from_email=To("fromemail@id")): # 新增:自动转换字符串为To对象 if isinstance(to_email, str): to_email = To(to_email) # 后续逻辑不变
修改后的示例代码
import os from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, Content, To sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) def send_mail(to_email, subject, message, from_email=To("fromemail@id")): """ Input : to_email (字符串或To对象) , subject , message字符串 , from_email Action: 向指定收件人发送邮件 """ try: if isinstance(to_email, str): to_email = To(to_email) content = Content("text/html", message) mail = Mail(from_email, to_email, subject, content) response = sg.send(mail) print(response.headers) print("响应状态码:", response.status_code) print(content) return True except Exception as e: print(f"错误详情: {e}") if hasattr(e, 'body'): print(f"错误响应体: {e.body}") return False # 调用示例 send_mail('toemail@example.com', 'testing', 'This is the message')
内容的提问来源于stack exchange,提问作者Kay Jey
相关产品推荐
相关产品推荐

