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