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

在尝试使用SendGrid的Python库发送带有PDF附件的电子邮件时遇到了400 Bad Request错误。问题出在编码PDF文件内容的方式上。通过修改代码,将PDF读取并使用base64编码,然后正确设置内容,解决了问题。对于Sendgrid v2或更低版本,可以使用编码后的文件内容直接设置;而对于v3及以上版本,需要先将编码后的数据解码。
摘要由CSDN通过智能技术生成

I'm trying to attach a PDF file to my email sent with sendgrid.

Here is my code :

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)

But the Sendgrid Python library is throwing an error HTTP Error 400: Bad Request.

What is wrong with my code ?

解决方案

I found a solution. I replaced this line :

pdf = open(pdf_path, "rb").read().encode("base64")

By this :

with open(pdf_path, 'rb') as f:

data = f.read()

encoded = base64.b64encode(data)

Now it works. I can send encoded file in the set_content :

attachment.set_content(encoded)

Note: The answer above works for Sendgrid v2 or lower. For v3 and up use:

encoded = base64.b64encode(data).decode()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值