简体   繁体   English

当尝试从 S3 发送文件作为 email 附件时,字节类型的 Object 不是 JSON 可序列化的

[英]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.

相关问题 将 json 文件从一个 s3 存储桶复制到另一个 s3 存储桶时,无法识别 Json 文件? - Json file is not recognising when copy json files from one s3 bucket to another s3 bucket? 如何从 S3 存储桶中获取文件,然后使用 Python 将其发送到 email? - How to get a file from an S3 bucket then send it over email using Python? Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 当试图从 api 路由中的 s3 中提取数据时 - Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 when trying to pull data from s3 in an api route stream json 来自 s3 存储桶的文件 - stream json file from s3 bucket 多个 object 通过在 s3 中仅打开一次 json 从 json 文件中删除 - Multiple object delete from json file by opening json only once in s3 从 S3 存储桶解析 JSON 文件 - Parsing a JSON file from a S3 Bucket 尝试从 AWS Lambda 访问 S3 时访问被拒绝 - Access Denied when trying to access S3 from AWS Lambda Rails aws s3 读取 email 和 csv 附件 - Rails aws s3 read email with csv attachment python pandas 从 s3 读取 json gzip 文件 - python pandas read json gzip file from s3 如何使用 Glue 作业将 JSON 从 s3 转换为 CSV 文件并将其保存在同一个 s3 存储桶中 - How to convert JSON to CSV file from s3 and save it in same s3 bucket using Glue job
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM