Python Sendgrid发送带有PDF附件文件的电子邮件

编程入门 行业动态 更新时间:2024-10-28 17:30:18
本文介绍了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") subject = "subject" to_email = Email("to@example") 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附件文件的电子邮件

本文发布于:2023-05-27 19:32:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/300544.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:词库加载错误:Could not find file 'D:\淘小白 高铁采集器win10\Configuration\Dict_Sto

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!