试图从S3将文件作为电子邮件附件发送时,bytes类型的对象不可JSON序列化

2024-04-25 10:16:59 发布

您现在位置:Python中文网/ 问答频道 /正文

错误消息:

"errorMessage": "Object of type bytes is not JSON serializable"

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)

Tags: nameobjdatagetobjects3pdfapplication
1条回答
网友
1楼 · 发布于 2024-04-25 10:16:59

您需要将文件内容编码为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)

相关问题 更多 >