通过python使用sendgrid时出现错误请求

通过python使用sendgrid时出现错误请求,python,sendgrid,Python,Sendgrid,尝试发送带有附件的电子邮件时,我从sendgrid收到错误的请求 导入base64 导入操作系统 导入json 从sendgrid导入SendGridApicClient 从sendgrid.helpers.mail导入( 邮件、附件、文件内容、文件名、, 文件类型、处置、内容ID) 将urllib.request导入为urllib 导入操作系统 导入json 从sendgrid导入SendGridApicClient 从sendgrid.helpers.mail导入邮件 信息=邮件( 来自xx

尝试发送带有附件的电子邮件时,我从sendgrid收到错误的请求

导入base64
导入操作系统
导入json
从sendgrid导入SendGridApicClient
从sendgrid.helpers.mail导入(
邮件、附件、文件内容、文件名、,
文件类型、处置、内容ID)
将urllib.request导入为urllib
导入操作系统
导入json
从sendgrid导入SendGridApicClient
从sendgrid.helpers.mail导入邮件
信息=邮件(
来自xxx@gmail.com',
到xxx@gmail.com',
主题=“使用Twilio SendGrid发送很有趣”,
html_content='并且在任何地方都可以轻松完成,即使使用Python也可以。)
文件路径='C:\\Users\\xxx\\OneDrive\\Desktop\\xxx.pdf'
打开(文件路径“rb”)作为f:
data=f.read()
f、 关闭()
encoded=base64.b64编码(数据).decode()
附件=附件()
attachment.file_content=文件内容(编码)
attachment.file_type=FileType('application/pdf')
attachment.file\u name=FileName('test\u FileName.pdf')
attachment.disposition=处置(“附件”)
attachment.content\u id=ContentId('PDF文档文件')
message.attachment=附件
尝试:
sendgrid\u client=SendGridAPIClient(os.environ.get('sendgrid\u API\u KEY'))
response=sendgrid\u client.send(消息)
打印(响应状态\ U代码)
打印(响应.正文)
打印(响应.标题)
例外情况除外,如e:
打印(电子邮件)
回溯(最近一次呼叫最后一次):
文件“”,第3行,在
文件“C:\Program Files(x86)\python\lib\site packages\sendgrid\sendgrid.py”,第98行,在send中
response=self.client.mail.send.post(请求\正文=message.get())
文件“C:\ProgramFiles(x86)\python\lib\site packages\python\u http\u client\client.py”,第262行,在http\u请求中
self.\u发出请求(开启器、请求、超时=超时)
文件“C:\Program Files(x86)\python\lib\site packages\python\u http\u client\client.py”,第178行,在请求中
加薪
python_http_client.exceptions.BadRequestsError:http错误400:错误请求

我假设这与我的pdf编码有关。我如何确保它是base64编码的?

不幸的是,即使这本身不是一个实际的“解决方案”,我也不能只发表评论。SendGrid可能会随BadRequest一起发送一条更有用的消息,您可以使用
HTTPError
查看该消息,如下所示:

from python_http_client.exceptions import HTTPError

sendgrid_client = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
try:
    response = sendgrid_client.send(message)
except HTTPError as e:
    print(e.to_dict)
发件人:

希望这能帮助你解决这个问题!错误代码的完整列表可在此处找到:


我看不出你的代码有什么特别的错误。今天我在试图解决我自己的问题时遇到了这个问题(肯定与您的经历无关),但是
base64.b64encode(data.decode())
与我的工作示例中的pdf完全相同。

您可以包含错误消息和堆栈吗?这不是解决问题的正确答案,但它确实有助于调试问题,使用“除python\u http\u client.exceptions.BadRequestsError as e:”可以很好地解决此问题,谢谢!