效果展示:
实现代码:
import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import os
def scan_file(path):
"""扫描文件"""
# 获取当前指定目录中的所有文件(文件夹+文件)
files = os.listdir(path)
# 遍历列表中的每个文件
for file in files:
# 拼接路径
file = os.path.join(path, file)
# 如果是文件,直接输出文件名称
if(os.path.isfile(file)):
f = open("D:/扫描结果.txt", mode="a", encoding="utf-8")
f.write(file)
f.close()
# 如果是文件夹,先输出文件夹名称
if(os.path.isdir(file)):
f = open("D:/扫描结果.txt", mode="a", encoding="utf-8")
f.write(file)
f.close()
# 递归调用
scan_file(file)
if __name__ == '__main__':
path = "D:"
scan_file(path)
# 设置SMTP服务器和端口
smtp_server = 'smtp.qq.com'
port = 465 # 或者使用587端口,但你可能需要使用tls()方法而不是ssl()方法
# 设置发件人和收件人信息
sender = '1730862718@qq.com' # 你的QQ邮箱地址
password = 'gieeqycxxdgbeahg' # 你生成的授权码
receivers = ['1730862718@qq.com'] # 收件人邮箱地址
# 创建邮件对象
message = MIMEMultipart()
# 设置邮件内容
subject = 'Hello, this is a test email from QQ'
f2 = open("D:/扫描结果.txt", encoding="utf-8")
d = f2.read()
content = d
# content = 'This is a test email sent from Python using QQ SMTP service.'
message['Subject'] = Header(subject, 'utf-8')
message['From'] = sender
message['To'] = ';'.join(receivers)
# 添加邮件正文
message.attach(MIMEText(content, 'plain', 'utf-8'))
# 连接到SMTP服务器并发送邮件
try:
with smtplib.SMTP_SSL(smtp_server, port) as server:
server.login(sender, password)
server.sendmail(sender, receivers, message.as_string())
print('Email sent successfully!')
except Exception as e:
print(f'Failed to send email: {e}')