如何在 Python 中将 pdf 文件附加到 MIME 电子邮件? [英] How to attach a pdf file to a MIME email in Python?

查看:89
本文介绍了如何在 Python 中将 pdf 文件附加到 MIME 电子邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个用于电子邮件营销的自动邮件发送程序(在 Python 3.6.1 中).我在附加 PDF 文件时遇到问题.邮件中PDF文件的文件名和页数是正确的,但PDF文件总是空白并且大小增加.我尝试了三种不同的方法,其他两种方法都不起作用.最后我决定在这里问它.感谢您的帮助.

I am making an automatic mail sending program (in Python 3.6.1) to use in email marketing. I am having an issue attaching PDF file. File name and page count of PDF file is correct in the mail but PDF file is always blank and its size increases.I tried three different ways, the other two ways didn't work. Last resort I decided to ask it here. Thanks for your help.

message = MIMEMultipart()
message['Subject'] = "Attachment Test"
message['From'] = 'myemail'
message['Reply-to'] = 'myemail'
message['To'] = 'otheremail'

text = MIMEText("Message Body")
message.attach(text)

directory = "C:\ExamplePDF.pdf"
with open(directory, encoding = 'utf-8', errors = 'replace') as opened:
    openedfile = opened.read()
attachedfile = MIMEApplication(openedfile, _subtype = "pdf", _encoder = encode_base64)
attachedfile.add_header('content-disposition', 'attachment', filename = "ExamplePDF.pdf")
message.attach(attachedfile)

server = SMTP("smtp.gmail.com:587")
server.ehlo()
server.starttls()
server.login("myemail", "password")
server.sendmail(message['From'], message['To'], message.as_string())
server.quit()

推荐答案

(答案摘自评论)
以二进制模式阅读您的 PDF:
with open("file.pdf", "rb") as open:

这篇关于如何在 Python 中将 pdf 文件附加到 MIME 电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆