Python Sendgrid发送带有PDF附件文件的电子邮件
问题内容:
我正在尝试将PDF文件附加到以sendgrid发送的电子邮件中。
这是我的代码:
sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
from_email = Email("from@example.com")
subject = "subject"
to_email = Email("to@example.com")
content = Content("text/html", email_body)
pdf = open(pdf_path, "rb").read().encode("base64")
attachment = Attachment()
attachment.set_content(pdf)
attachment.set_type("application/pdf")
attachment.set_filename("test.pdf")
attachment.set_disposition("attachment")
attachment.set_content_id(number)
mail = Mail(from_email, subject, to_email, content)
mail.add_attachment(attachment)
response = sg.client.mail.send.post(request_body=mail.get())
print(response.status_code)
print(response.body)
print(response.headers)
但是,Sendgrid Python库抛出错误HTTP错误400:错误的请求。
我的代码有什么问题?
问题答案:
我找到了解决方案。我替换了这一行:
pdf = open(pdf_path, "rb").read().encode("base64")
这样 :
with open(pdf_path, 'rb') as f:
data = f.read()
encoded = base64.b64encode(data)
现在可以了。我可以在set_content中发送编码文件:
attachment.set_content(encoded)
注意: 以上答案适用于Sendgrid v2或更低版本。对于v3及更高版本:
encoded = base64.b64encode(data).decode()