【问题标题】:How to find individual files and email file location in python如何在 python 中查找单个文件和电子邮件文件位置
【发布时间】:2017-05-23 14:59:09
【问题描述】:

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

干杯,

【问题讨论】:

    标签: python filepath smtplib os.path


    【解决方案1】:

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

    【讨论】:

    • 您可以将os.path.splitext(fullpath)[1] == '.txt' 替换为fullpath.endswith(".txt")
    猜你喜欢
    • 2015-09-27
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    • 2012-01-11
    • 2015-07-30
    相关资源
    最近更新 更多