[英]Object of type bytes is not JSON serializable when trying to send a file from S3 as an email attachment
Error message:错误信息:
"errorMessage": "Object of type bytes is not JSON serializable"
"errorMessage": "bytes 类型的对象不是 JSON 可序列化的"
def _get_file():
s3 = boto3.resource('s3')
obj = s3.Object(S3_BUCKET_NAME, S3_ITEM_NAME)
return obj.get()['Body'].read()
def _send_email_with_ebook(email):
data = {
...
"attachments": [
{
"content": _get_ebook_file(),
"type": "application/pdf",
"filename": "my_file.pdf"
}
]
}
headers = {'Authorization': 'Bearer {}'.format(SENDGRID_API_KEY), 'Content-Type': 'application/json'}
r = requests.post(SENDGRID_API_URL, json=data, headers=headers)
You need encode to base64 your file content for example:您需要将文件内容编码为 base64,例如:
import base64
def _get_file():
s3 = boto3.resource('s3')
obj = s3.Object(S3_BUCKET_NAME, S3_ITEM_NAME)
return obj.get()['Body'].read()
def _send_email_with_ebook(email):
data = {
...
"attachments": [
{
"content": base64.b64encode(_get_ebook_file()),
"type": "application/pdf",
"filename": "my_file.pdf"
}
]
}
headers = {'Authorization': 'Bearer {}'.format(SENDGRID_API_KEY), 'Content-Type': 'application/json'}
r = requests.post(SENDGRID_API_URL, json=data, headers=headers)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.