使用 SMTP 发送 xlsx 文件 & Python 3

Sending xlsx file using SMTP & Python 3

当我将文件名附加到电子邮件并发送时,我无法让 SMTP 服务器保留我的文件名。我 运行 这两次,效果很好。名称和 excel sheet 按预期显示。现在,无论我做什么,附件在以前正常工作时总是类似于 ATT00001.xlsx。 (实际上是留给午休时间,当我回来时没有任何更改,然后重新 运行 它)我想知道我是否是这样将 excel sheet 附加到我的电子邮件中的。有人会碰巧知道这是怎么回事吗?谢谢!

msg = MIMEMultipart()
sender='email@email.org'
recipients='email@recipient.org'
server=smtplib.SMTP('mail.server.lan')

msg['Subject']='Quarterly Summary'
msg['From']=sender
msg['To']=recipients



filename = r'C:\Users\user.chad\Quarterly\project\output\MyData.xlsx'
attachment = open(r'C:\Users\user.chad\Quarterly\project\output\MyData.xlsx', 'rb')
xlsx = MIMEBase('application','vnd.openxmlformats-officedocument.spreadsheetml.sheet')
xlsx.set_payload(attachment.read())

encoders.encode_base64(xlsx)
xlsx.add_header('Content-Dispolsition', 'attachment', filename=filename)
msg.attach(xlsx)

server.sendmail(sender, recipients, msg.as_string())
server.quit()
attachment.close()

仅作记录:

xlsx.add_header('Content-Dispolsition', 'attachment', filename=filename)

应该是

xlsx.add_header('Content-Disposition', 'attachment', filename=filename)

这是添加内容为 text/html 的附件的示例。

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

message = MIMEMultipart()

# add text
message.attach(
    MIMEText(
        content,
        'html',
        'utf-8'
        )
    )

# add attachment
attachment = MIMEBase('application', "octet-stream")
# open a file to attach
attachment.set_payload(open(filepath, "rb").read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment; filename="%s"' % self.filename )
message.attach(attachment)


server.sendmail(SENDER, receivers, message.as_string())