Python Sendgrid发送带有PDF附件文件的电子邮件 [英] Python Sendgrid send email with PDF attachment file
本文介绍了Python Sendgrid发送带有PDF附件文件的电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将PDF文件附加到通过sendgrid发送的电子邮件中.
I'm trying to attach a PDF file to my email sent with 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:错误的请求.
But the Sendgrid Python library is throwing an error HTTP Error 400: Bad Request.
我的代码有什么问题?
推荐答案
我找到了解决方案.我替换了这一行:
I found a solution. I replaced this line :
pdf = open(pdf_path, "rb").read().encode("base64")
通过这个:
with open(pdf_path, 'rb') as f:
data = f.read()
encoded = base64.b64encode(data)
现在可以使用了.我可以在set_content中发送编码文件:
Now it works. I can send encoded file in the set_content :
attachment.set_content(encoded)
注意:上面的答案适用于Sendgrid v2或更低版本.对于v3及更高版本:
Note: The answer above works for Sendgrid v2 or lower. For v3 and up use:
encoded = base64.b64encode(data).decode()
这篇关于Python Sendgrid发送带有PDF附件文件的电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文