有趣的名字/不完整的附件/错误的扩展名 - Mail Python

时间:2016-04-13 15:36:09

标签: python email

我从具有三个csv文件的目录路径发送来自linux盒子的邮件。我想在我的电子邮件中附上所有这三个。下面是脚本。

def mailer(sender, to, path):

    msg = MIMEMultipart()
    msg['Subject'] = 'UMR_EOD_RECONCILLATIONS'
    msg['From']    = sender
    msg['To']      = to

    for file in os.listdir(path):
        f = open( path + file, 'rb')
        csv = MIMEText(f.read())
        f.close()
        msg.attach(csv)

    mailer = smtplib.SMTP('localhost')
    mailer.sendmail(sender,to, msg.as_string())
    mailer.quit()

我一直在摸不着头脑,多次尝试但仍面临以下问题。

  • 附加的文件是文本文件,即.txt扩展名,我想要的是csv
  • 文件的名称ATT00001.txtATT00002.txt有趣,但仍保持不变。
  • 第三个文件永远不会附加到邮件中,它的内容在正文中输出,而且这是该死的同一文件,但我可能会尝试。

我试过设置如下,但无济于事。

msg["Content-Disposition"] = "attachment; filename=" + file + ";"

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

2 个答案:

答案 0 :(得分:3)

1)第一个文本对象将显示为电子邮件消息。因此,首先添加一个额外的文本对象。

2)CSV文件应以content-type: text/plain传输,而不是#UNTESTED def mailer(sender, to, path): msg = MIMEMultipart() msg['Subject'] = 'UMR_EOD_RECONCILLATIONS' msg['From'] = sender msg['To'] = to msg.attach(MIMEText('Here are the reports you asked for.')) for file in os.listdir(path): f = open( path + file, 'rb') csv = MIMEText(f.read(), 'csv') f.close() csv.add_header('Content-Disposition', 'attachment', filename=file) msg.attach(csv) mailer = smtplib.SMTP('localhost') mailer.sendmail(sender,to, msg.as_string()) mailer.quit()

services.AddScoped<MetaWeblogModelMapper, MetaWeblogModelMapper>();

答案 1 :(得分:2)

当你只想发送电子邮件时,我总是建议你从做的东西开始。我觉得没有人想要解决这个问题。感觉就像Java。

试试yagmail;道歉,我是开发人员。

其目的是使用HTML,内联图像和附件发送电子邮件变得非常容易。

您想要的代码:

import os
import yagmail

def mailer(sender, to, path):
    yag = yagmail.SMTP(sender, host="localhost", smtp_skip_login=True)
    contents = ['Here are the reports you asked for.'] + os.listdir(path)
    yag.send(to, 'UMR_EOD_RECONCILLATIONS', contents)

我建议在README阅读更多精彩的技巧:)

要开始使用,请使用pip install yagmail安装yagmail。