我正在从具有三个 csv 文件的目录路径中的 linux box 发送邮件。我想在我的电子邮件中附上所有三个。下面是脚本。
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.txt和ATT00002.txt保持不变。 - 第三个文件永远不会附加到邮件中,它的内容在正文中输出,无论我尝试多少次,它都是同一个文件。
我试过下面的设置,但没有用。
msg["Content-Disposition"] = "attachment; filename=" + file + ";"
msg.add_header('Content-Disposition', 'attachment', filename=file)
请您参考如下方法:
1) 第一个文本对象将显示为电子邮件消息。因此,首先添加一个额外的文本对象。
2) CSV 文件应作为content-type: text/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()
