使用SendGrid发送JSON附件时遇bytes类型无法JSON序列化错误
SendGrid添加JSON附件时报错:Object of type bytes is not JSON serializable
问题分析
你遇到的错误核心原因是:base64.b64encode()返回的是bytes类型对象,但SendGrid API在序列化请求体时,只能处理JSON可序列化的类型(比如字符串)。直接将bytes传入Attachment的file_content参数(即使包装了FileContent类),会触发JSON序列化失败。
解决步骤
关键修正点是将Base64编码后的bytes对象转换为UTF-8字符串,具体操作如下:
- 对
base64.b64encode()的结果调用.decode('utf-8'),得到字符串格式的Base64内容 - 确保正确导入SendGrid的邮件辅助类(正确路径是
sendgrid.helpers.mail,而非直接从sendgrid导入)
修正后的完整代码
import json import base64 from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, Attachment, FileContent, FileName, FileType # 准备要作为附件的JSON数据 final_data = {"user":{"email": "test@gmail.com", "username": "test1"}} # 1. 将Python字典转为JSON字符串 json_str = json.dumps(final_data) # 2. 编码为UTF-8字节 → Base64编码 → 转换为字符串 base64_content = base64.b64encode(json_str.encode("utf-8")).decode("utf-8") # 3. 构建附件对象 attachment = Attachment( file_content=FileContent(base64_content), file_name=FileName("user.json"), file_type=FileType("application/json") ) # 4. 构建邮件并添加附件 message = Mail( from_email="your-sender-email@example.com", to_emails="recipient-email@example.com", subject="JSON附件测试", plain_text_content="请查收附件中的JSON数据。" ) message.add_attachment(attachment) # 5. 发送邮件 sg = SendGridAPIClient("your-sendgrid-api-key") response = sg.send(message)
额外说明
- 旧版SendGrid文档可能存在导入路径错误,务必从
sendgrid.helpers.mail导入Mail、Attachment等类,避免因类结构不匹配导致的隐性问题 - Base64编码后的内容必须是字符串,这是SendGrid API要求的格式,bytes类型无法被正确序列化
内容的提问来源于stack exchange,提问作者Tom3652
相关产品推荐
相关产品推荐

