我正在try 使用sendgrid包以JSON文件的形式发送一个pythondict作为邮箱附件.

以下是代码:

from sendgrid import SendGridAPIClient
from sendgrid import Mail
from sendgrid import Email
from sendgrid import Attachment

final_data = {"user":{"email": "test@gmail.com", "username": "test1"}}
result = json.dumps(final_data)
print(f"Result type {type(result)}")
encoded = base64.b64encode(result.encode("utf-8"))
print(f"encoded : {encoded}")
attachment = Attachment(file_content=encoded, file_name="user.json", file_type="application/json")
message.add_attachment(attachment)
sg.send(message)

sg.send(message)行抛出错误:Object of type bytes is not JSON serializable

我见过这么多关于如何编码到base64的问题,但我确实做到了,下面是这个代码片段的全部痕迹:

Result type <class 'str'>
encoded : b'eyJ1c2VyIjogeyJsYXN0TmFtZSI6ICJCb2JvIiwgImZpcnN0TmFtZSI6ICJCb2JvIiwgImVtYWlsIjogImJvcmlzLmZhcmVsbEBnbWFpbC5jb20iLCAidGVsIjogIiIsICJiaXJ0aGRhdGUiOiAwLCAicGhvdG9VcmwiOiAiaHR0cHM6Ly9zdG9yYWdlLmdvb2dsZWFwaXMuY29tL2luZmVlbGliL2RvY3VtZW50cy91c2Vycy9qVHBBdGRBS1lCV2V2YWUwajJLVHBSalByeUMzL3Byb2ZpbGUvMGE0ZTQzYjEtMWQzZS00ODk0LWJjYWItNGFkYTFhZDY3ODFkLmpwZz9YLUdvb2ctQWxnb3JpdGhtPUdPT0c0LVJTQS1TSEEyNTYmWC1Hb29nLUNyZWRlbnRpYWw9ZmlyZWJhc2UtYWRtaW5zZGstbmU0emElNDBpbmZ0ZWFtLWkuaWFtLmdzZXJ2aWNlYWNjb3VudC5jb20lMkYyMDIzMDcwOSUyRmF1dG8lMkZzdG9yYWdlJTJGZ29vZzRfcmVxdWVzdCZYLUdvb2ctRGF0ZT0yMDIzMDcwOVQxMDQ2MDlaJlgtR29vZy1FeHBpcmVzPTYwNDgwMCZYLUdvb2ctU2lnbmVkSGVhZGVycz1ob3N0JlgtR29vZy1TaWduYXR1cmU9Mjk2MjY4MjY1MTA3NGMyN2VkMmY5MmY1YzBkYWM4N2JhYTIzODY0N2Q4NzFhYTk3ZTIyZmE3ZjE5MjcyNWEwN2ZiN2U4NzAxZGU4ZmJlYmIyOGZiMWVmZjdlMWY5MGQ3NzZmNTU3OTRiMTVlOTEwMzkyMTM0MmNlNzE4YzQ5ZWZjOTdlNjk1Njk3YTg0Nzk5OTQyODY4NDliMjcyYmZmMzdjM2I0MzE5ZWM1NmZlNDk2N2YzZDczM2Q5ZTMzZWMxZjJjOWFiZTUyYjA2OWJhZmU0MTA5OTMxMWFhYmQ4MTU2MzgyNDVmZWYzYjdhNzY5M2I2OGE3Njc3NzFhMjZkYWIzY2E1NGRkZDdkYTJlYTJlYTcyZjZlOGE5YmYzYjJiNTZjOWNiOTdmZTZhOTZiZjczYjI5ZTNiN2E5YTlmODI1ZDA3MTkxNWIwYTQ1ZWYwZjE1MmJmOTEyYzQxNmVlYThmOWEzZGIyNDg3ZTc4YzIxYTM3MGZiZmYxMzg4NDZhMTI3ZDk5NDk4NTQzZGIyYzA1ZjFmNGNmMjc4YTQ3MTg2MTM0ODczZTAxNzY5ZmU4YzliNjIxMmRmMTdiZjI1NDQ2Y2RkM2M2NjgyZjNmZWIyMThiMTZkNTNmZWU0YTU3ODhjOTAxMWRlNTA5NjExZjY5MjI1Yzk5NmUwNWRhNmUifX0='
ERROR:root:export_all_data: Object of type bytes is not JSON serializable

编辑:

我已将我的代码更改为使用:

from sendgrid import FileContent
from sendgrid import FileName
from sendgrid import FileType
attachment = Attachment(file_content=FileContent(encoded), file_name=FileName("user.json"),
                                file_type=FileType("application/json"))

根据documentation,但不幸的是,它仍然失败.

推荐答案

ERROR:root:export_all_data: Object of type bytes is not JSON serializable

Looking at sendgrid-python / use cases / attachment, I see there is that the SendGrid API requires the base64-encoded attachment to be in a string format, not in bytes.
After calling base64.b64encode(result.encode("utf-8")), it will return a bytes object, which is not JSON serializable. Therefore, you need to decode the bytes to string before passing it to the FileContent().

在你的问题中,我看不到"decode()".

You can see that change in this updated code:
(but also illustrated in "Python Sendgrid send email with PDF attachment file")

from sendgrid import SendGridAPIClient
from sendgrid import Mail
from sendgrid.helpers.mail import Email, To, Content, Attachment, FileContent, FileName, FileType

import json
import base64

final_data = {"user":{"email": "test@gmail.com", "username": "test1"}}
result = json.dumps(final_data)
print(f"Result type {type(result)}")

# base64 encode the json string and decode the bytes to string
encoded = base64.b64encode(result.encode("utf-8")).decode()

print(f"encoded : {encoded}")

# Initialize a Mail object
email = Mail(
    from_email=Email('your-email@example.com'),
    to_emails=To('test@gmail.com'),
    subject='Subject',
    plain_text_content='Content',
)

# Attach the file
attachment = Attachment()
attachment.file_content = FileContent(encoded)
attachment.file_name = FileName("user.json")
attachment.file_type = FileType("application/json")
email.add_attachment(attachment)

# Use your SendGrid API key
sg = SendGridAPIClient('your_sendgrid_api_key')

# Send the email
response = sg.send(email)

请务必将'your-email@example.com''your_sendgrid_api_key'替换为您的实际邮箱和SendGrid API密钥.

Python相关问答推荐

Python plt.text中重叠,包adjust_text不起作用,如何修复?

如何在Deliveryter笔记本中从同步上下文正确地安排和等待Delivercio代码中的结果?

如何使用scipy从频谱图中回归多个高斯峰?

通过优化空间在Python中的饼图中添加标签

Odoo 14 hr. emergency.public内的二进制字段

重新匹配{ }中包含的文本,其中文本可能包含{{var}

将两只Pandas rame乘以指数

ODE集成中如何终止solve_ivp的无限运行

如何在WSL2中更新Python到最新版本(3.12.2)?

使用密钥字典重新配置嵌套字典密钥名

如何在表中添加重复的列?

在嵌套span下的span中擦除信息

处理具有多个独立头的CSV文件

Pandas:计算中间时间条目的总时间增量

如何创建引用列表并分配值的Systemrame列

Python避免mypy在相互引用中从另一个类重定义类时失败

Pandas 数据帧中的枚举,不能在枚举列上执行GROUP BY吗?

如何根据一定条件生成段id

将数字数组添加到Pandas DataFrame的单元格依赖于初始化

将数据从一个单元格保存到Jupyter笔记本中的下一个单元格