利用python发送邮件

题目要求:

编写python代码,扫描指定目录下的文件,将这些扫描的文件内容以邮件发送送到指定邮箱

代码内容如下:

注意:

1.发送邮件之前需要将qq邮箱的授权码设置正确

2.确定邮箱正确,以及扫描文件的位置正确

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

def scan_file(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 += scan_file(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(sender_email, sender_password, recipient, subject, body):
    # SMTP服务器信息(以QQ邮箱为例)
    smtp_server = 'smtp.qq.com'
    smtp_port = 465

    # 创建SMTP会话
    server = smtplib.SMTP_SSL(smtp_server, smtp_port)
    server.login(sender_email, sender_password)

    # 构建邮件内容
    message = MIMEText(body, 'plain', 'utf-8')
    message['Subject'] = subject
    message['From'] = sender_email
    message['To'] = recipient

    # 发送邮件
    server.sendmail(sender_email, recipient, message.as_string())

    # 关闭SMTP会话
    server.quit()

if __name__ == '__main__':
    path = "D:\xx\xx"
    # 扫描文件并收集结果
    file_tree = scan_file(path)

    # 发送邮件
    sender_email = 'xxxxxxxxxxx@qq.com'
    sender_password = 'xxxxxxxxxxx'#此处为授权码
    recipient = 'xxxxxxxxxx@qq.com'
    subject = '文件树形结构'
    send_email(sender_email, sender_password, recipient, subject, file_tree)

 运行结果如下:

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值