Python扫描发送邮件

一、具体要求

编写 python 代码,扫描指定的目录下的所有文件,将这些扫描的文本内容邮 件发送到指定邮箱( 自己的 qq 邮箱 )
示例如下:
使用QQ邮箱SMTP服务器需要获取QQ邮箱授权码,获取方式可参考以下链接:

二、相关代码

import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def list_files_recursively(path, depth=0):
    """扫描文件并打印树形结构"""
    indent = "    " * depth
    files = sorted(os.listdir(path))
    file_tree = ""
    for f in files:
        fullpath = os.path.join(path, f)
        if os.path.isdir(fullpath):
            file_tree += f"{indent}├── {f}/\n"
            file_tree += list_files_recursively(fullpath, depth + 1)
            if depth == 0 and f < files[-1]:
                file_tree += f"{indent}│   \n"
        elif os.path.isfile(fullpath):
            file_tree += f"{indent}├── {f}\n"
            if depth == 0 and f < files[-1]:
                file_tree += f"{indent}│   \n"
    return file_tree
def send_email(subject, body, to_email, from_email, password, smtp_server, smtp_port):
    # 创建邮件对象
    msg = MIMEMultipart()
    msg['From'] = from_email
    msg['To'] = to_email
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain', 'utf-8'))
    #SMTP 服务器
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()
    server.login(from_email, password)
    server.sendmail(from_email, to_email, msg.as_string())
    server.quit()


if __name__ == '__main__':
    # 已经的一个文件夹路径
    folder_path = "D:\\Typora"
    tree_string = list_files_recursively(folder_path)
    send_email(
        "文件夹树形结构",
        tree_string,
        "**********@qq.com",  # 收件人邮箱
        "**********@qq.com",  # 发件人邮箱(确保这个邮箱与你的SMTP账户一致)
        "***********",  # 此处填写你的QQ邮箱SMTP授权码
        "smtp.qq.com",
        587
    )

三、执行结果展示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值