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



我正在尝试使用 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 附件。

我希望它为找到的每个 *.txt 文件发送一封单独的电子邮件。任何帮助将不胜感激。

干杯

为循环中的每个.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()

最新更新