如何在python中查找单个文件和电子邮件文件位置

时间:2017-05-23 14:59:10

标签: python filepath smtplib os.path

我正在尝试使用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文件发送一封单独​​的电子邮件。任何帮助都将非常感激。

干杯,

1 个答案:

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