【重复】SendGrid-Python 报错 TypeError: Object of type Email is not JSON serializable

import sendgrid
import os
from sendgrid.helpers.mail import *


def send_email(subject, to, body):
    sg = sendgrid.SendGridAPIClient(api_key=os.getenv('SENDGRID_API_KEY'))
    from_email = Email('andyforever0108@outlook.com')
    to_email = Email(to)
    content = Content("text/plain", body)
    mail = Mail(from_email, subject, to_email, content)
    response = sg.client.send.post(request_body=mail.get())

在自己的项目中使用这个函数的时候遇到
File “e:\python\lsfd202201v3\venv\lib\site-packages\flask_compat.py”, line 39, in reraise
raise value
File “e:\python\lsfd202201v3\venv\lib\site-packages\flask\app.py”, line 1950, in full_dispatch_request
rv = self.dispatch_request()
File “e:\python\lsfd202201v3\venv\lib\site-packages\flask\app.py”, line 1936, in dispatch_request
return self.view_functionsrule.endpoint
File “E:\Python\LSFD202201V3\app.py”, line 97, in upload_result
send_email(
File “E:\Python\LSFD202201V3\send_email.py”, line 11, in send_email
response = sg.client.send.post(request_body=mail.get())
File “e:\python\lsfd202201v3\venv\lib\site-packages\python_http_client\client.py”, line 251, in http_request
data = json.dumps(request_body).encode(‘utf-8’)
File “D:\Python\Python38\lib\json_init_.py”, line 231, in dumps
return _default_encoder.encode(obj)
File “D:\Python\Python38\lib\json\encoder.py”, line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File “D:\Python\Python38\lib\json\encoder.py”, line 257, in iterencode
return _iterencode(o, 0)
File “D:\Python\Python38\lib\json\encoder.py”, line 179, in default
raise TypeError(f’Object of type {o.class.name} ’
TypeError: Object of type Email is not JSON serializable

我用的是 Outlook.com,请问是Outlook.com的格式问题吗?

发帖前建议先搜索

https://codekitchen.community/t/topic/451

另外你的标题也太简陋了,下次拜托写一个包含关键信息的标题,比如「sendgrid 发送邮件报错TypeError: Object of type Email is not JSON serializable」。

不好意思,初来乍到

1 个赞

对了,建议用示例程序的依赖文件来一次安装所有依赖:

$ pip install -r requirements.txt

或:

$ pipenv install --dev

这样所有依赖的版本都会对应书里介绍的版本。

谢谢

不客气 : )