使用Python发送邮件时,通过SendGrid出现“Bad Request”错误

7

当我试图发送附件邮件时,从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编码的?

请问您能否包含错误信息和堆栈? - Fernando Zamperin
1个回答

18

很不幸,虽然这不是一个实际的“解决方案”,但我不能只评论。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的工作示例中完全相同。


这不是修复问题的正确答案,但它肯定有助于调试问题。 - Muthu Kumar
1
使用"except python_http_client.exceptions.BadRequestsError as e:"很好用,谢谢! - Flo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接