【问题标题】:How to attach a pdf file to a MIME email in Python?如何在 Python 中将 pdf 文件附加到 MIME 电子邮件?
【发布时间】:2017-11-07 08:28:30
【问题描述】:

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

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 opened: ...
  • 非常感谢,成功了!
  • 您可以将此添加为答案并将其标记为已接受,以便其他人更容易找到它。

标签: python-3.x mime


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-07-09
    • 2014-07-01
    • 2015-05-28
    • 2020-11-21
    • 2016-06-13
    • 2023-03-07
    • 2021-10-13
    • 1970-01-01
    • 2019-04-06
    相关资源
    最近更新 更多