我正在尝试使用python执行2个函数。第一个功能是查找目录结构中所有* .txt文件的目录路径。第二种是将文件目录路径发送到电子邮件正文中的电子邮件地址。
import smtplib
import os, os.path
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
fromaddr = "server@company.com"
toaddr = "user@company.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "New message"
for root, dirs, files in os.walk("/var/logs"):
for f in files:
fullpath = os.path.join(root, f)
if os.path.splitext(fullpath)[1] == '.txt':
body = "Path = %s" % fullpath
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('mail.company.com',25)
server.ehlo()
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
我取得了一些成功,但它没有按照我的意愿行事。目前,电子邮件通过电子邮件正文中的一个文件路径到达,另一个文件路径作为电子邮件的附件附件。
我希望它为找到的每个* .txt文件发送一封单独的电子邮件。任何帮助都将非常感激。
干杯,
本
答案 0 :(得分:0)
为循环内的每个.txt文件创建并发送新消息。像这样:
import smtplib
import os, os.path
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
fromaddr = "server@company.com"
toaddr = "user@company.com"
server = smtplib.SMTP('mail.company.com',25)
server.ehlo()
for root, dirs, files in os.walk("/var/logs"):
for f in files:
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "New message"
fullpath = os.path.join(root, f)
if os.path.splitext(fullpath)[1] == '.txt':
body = "Path = %s" % fullpath
msg.attach(MIMEText(body, 'plain'))
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()