我在尝试发送带有附件的电子邮件时收到来自 sendgrid 的错误请求错误
import base64
import os
import json
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (
Mail, Attachment, FileContent, FileName,
FileType, Disposition, ContentId)
import urllib.request as urllib
import os
import json
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
message = Mail(
from_email='xxx@gmail.com',
to_emails='xxx@gmail.com',
subject='Sending with Twilio SendGrid is Fun',
html_content='<strong>and easy to do anywhere, even with Python</strong>')
file_path = 'C:\\Users\\xxx\\OneDrive\\Desktop\\xxx.pdf'
with open(file_path, 'rb') as f:
data = f.read()
f.close()
encoded = base64.b64encode(data).decode()
attachment = Attachment()
attachment.file_content = FileContent(encoded)
attachment.file_type = FileType('application/pdf')
attachment.file_name = FileName('test_filename.pdf')
attachment.disposition = Disposition('attachment')
attachment.content_id = ContentId('PDF Document file')
message.attachment = attachment
try:
sendgrid_client = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
response = sendgrid_client.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
except Exception as e:
print(e.message)
Run Code Online (Sandbox Code Playgroud)
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "C:\Program Files (x86)\python\lib\site-packages\sendgrid\sendgrid.py", line 98, in send
response = self.client.mail.send.post(request_body=message.get())
File "C:\Program Files (x86)\python\lib\site-packages\python_http_client\client.py", line 262, in http_request
self._make_request(opener, request, timeout=timeout)
File "C:\Program Files (x86)\python\lib\site-packages\python_http_client\client.py", line 178, in _make_request
raise exc
python_http_client.exceptions.BadRequestsError: HTTP Error 400: Bad Request
Run Code Online (Sandbox Code Playgroud)
我假设它与我的 pdf 的编码有关。我如何确保它是 base64 编码的?
小智 9
不幸的是,即使这本身并不是一个实际的“解决方案”,我也不能只是发表评论。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)
Run Code Online (Sandbox Code Playgroud)
来自:https : //github.com/sendgrid/sendgrid-python/blob/master/TROUBLESHOOTING.md#error
希望这将帮助您真正解决问题!可以在此处找到错误代码的完整列表:https : //sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html
我没有看到您显示的代码有什么特别错误。我今天遇到了这个问题,试图解决我自己的问题(绝对与您遇到的问题无关),但base64.b64encode(data).decode()与我在 pdf 工作示例中遇到的问题完全相同。
| 归档时间: |
|
| 查看次数: |
1730 次 |
| 最近记录: |