以下是一个用Python实现最新文件检测工具的示例代码:

import os
import time
import smtplib
from email.mime.text import MIMEText

# 监控目录
monitor_dir = '/path/to/monitor/directory'

# 发件人邮箱
sender = 'your_email@example.com'

# 收件人邮箱,可以是多个
recipients = ['recipient1@example.com', 'recipient2@example.com']

# 邮件服务器地址和端口
smtp_server = 'smtp.example.com'
smtp_port = 587

# 邮箱账户和密码
smtp_username = 'your_email@example.com'
smtp_password = 'your_email_password'

# 上次检测的最新文件时间戳
last_modified_time = 0

while True:
    # 获取目录下的所有文件
    files = os.listdir(monitor_dir)

    # 获取最新的文件时间戳
    latest_modified_time = max([os.path.getmtime(os.path.join(monitor_dir, f)) for f in files])

    # 如果有新文件出现
    if latest_modified_time > last_modified_time:
        # 更新最新文件时间戳
        last_modified_time = latest_modified_time

        # 构造邮件内容
        text = 'New file detected in {} at {}.'.format(monitor_dir, time.strftime('%Y-%m-%d %H:%M:%S'))
        message = MIMEText(text)
        message['Subject'] = 'New File Detected'
        message['From'] = sender
        message['To'] = ','.join(recipients)

        # 发送邮件
        with smtplib.SMTP(smtp_server, smtp_port) as server:
            server.starttls()
            server.login(smtp_username, smtp_password)
            server.send_message(message)

    # 休眠5秒后再进行下一次检测
    time.sleep(5)

该代码会不断地监测指定目录下是否有新文件出现,如果有则会发送一封邮件通知收件人。如果目录下一开始就没有任何文件,则程序会一直等待直到有新文件出现。如果想要程序在启动时也能够发送一封邮件通知,可以在循环外先进行一次检测并发送邮件

用Python写一个最新文件检测工具如不存在文件则邮件推送消息

原文地址: https://www.cveoy.top/t/topic/gAuf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录