通过python使用sendgrid时遇到错误的请求错误

时间:2019-10-04 20:54:04

标签: python sendgrid

在尝试发送带有附件的电子邮件时,我从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)
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

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

1 个答案:

答案 0 :(得分:0)

不幸的是,即使这本身不是一个实际的“解决方案”,我也不能发表评论。 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)

来自: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的示例中完全相同。