【问题标题】:Sending xlsx file using SMTP & Python 3使用 SMTP 和 Python 3 发送 xlsx 文件
【发布时间】:2019-01-08 06:41:17
【问题描述】:

我无法让 SMTP 服务器保留我的文件名,因为我将它们附加到电子邮件并发送它们。我跑了两次,效果很好。名称和 Excel 表按预期显示。现在,无论我做什么,附件总是像 ATT00001.xlsx 一样,当它过去工作得很好时。 (字面意思是午休时间,当我回来时重新运行它,没有任何变化)我想知道这是否是我将 Excel 表附加到我的电子邮件的方式。有人会碰巧知道这是怎么回事吗?谢谢!

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()

【问题讨论】:

  • 你确定它是 Content-dispolsition 吗?我有类似的东西: with open(attachment, "rb") as attach: part = MIMEApplication( attach.read(), Name=os.path.basename(attachment) ) part['Content-Disposition'] = 'attachment; filename="{}"'.format(os.path.basename(attachment)) msg​​.attach(part)
  • @E.Serra duuuuuuude。拼写错误。谢谢你。如果您将此作为答案发布,我会给您信用。
  • 没问题的朋友,乐于助人

标签: python excel smtp smtplib


【解决方案1】:

仅作记录:

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

应该是

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

【讨论】:

    【解决方案2】:

    这是一个添加带有 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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-09
      • 1970-01-01
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-13
      相关资源
      最近更新 更多