【问题标题】:Sending mail with (docx)attachment using python使用python发送带有(docx)附件的邮件
【发布时间】:2021-12-03 14:13:18
【问题描述】:

我一直在尝试通过 python 发送带有 Docx 附件的邮件

我可以收到一封邮件,但没有附件,下面是我用来附加文件的代码 而且我在附加文件时没有收到任何错误

import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

sender_email = email
receiver_email = toemail
password = password

message = MIMEMultipart("alternative")
message["Subject"] = Subject
message["From"] = sender_email
message["To"] = receiver_email
message.attach(htmlmessage)

attach_file = open(attach_file_name, 'rb') # Open the file as binary mode
payload = MIMEBase('application', 'octet-stream')
payload.set_payload((attach_file).read())
encoders.encode_base64(payload)
#encode the attachment
#add payload header with filename
payload.add_header('Content-Disposition', "attachment; filename= %s" % attach_file)
message.attach(payload)

context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
    server.login(sender_email, password)
    server.sendmail(
        sender_email, receiver_email, message.as_string()
    )




【问题讨论】:

标签: python email docx mime


【解决方案1】:

要尊重 Mime 类型。 multipart/alternative 类型应该用于包含相同信息的纯文本和 HTML 消息。然后,邮件阅读器可以选择它可以使用的表示形式。

另一方面,当消息包含多个不同部分时,应该使用multipart/mixed,以不同方式传输附件

因此,如果htmlmessage 是有效的email.mime.text.MIMEText,您的代码不应声明"alternative"

...
message = MIMEMultipart()
...

此外,您应该避免直接使用MIMEBase,而是依赖MIMEApplication 的默认值:

payload = MIMEApplication(attach_file.read(),
                'vnd.openxmlformats-officedocument.wordprocessingml.document')
payload.add_header('Content-Disposition',
                   "attachment; filename= %s" % attach_file)
message.attach(payload)

但我必须承认,最后一点主要是品味问题......

【讨论】:

  • 感谢第一部分,这确实解决了附件问题。但我附加的 docx 文件似乎显示为损坏的文件。我尝试使用您的 MIMEApplication 而不是 MIMEBase 但仍然附加的文件已损坏。即使我使用 MIMEBase,附件仍然是相同的损坏
    有一些 docx python 帮助说 Docx 是来自 StackOverflow
    的压缩二进制格式
  • @oneclick 我的错。我没有足够注意文件的类型,而是使用了MIMEApplication 的默认值,因为您的代码最初使用了 application/octet-stream mime 类型。根据 [this other SO post],docx 文件的类型应为application/vnd.openxmlformats-officedocument.wordprocessingml.document。我用正确的子类型编辑了我的帖子。
猜你喜欢
  • 1970-01-01
  • 2020-09-16
  • 1970-01-01
  • 2014-11-09
  • 2017-02-04
  • 2020-06-22
  • 2012-05-24
  • 1970-01-01
相关资源
最近更新 更多