以下是处理邮件附件的 Python 代码示例:

import os
import email
import re
import base64

# 附件保存路径
save_path = os.path.expanduser('~/Desktop')

# 邮件文件夹路径
mail_folder = os.path.expanduser('~/Maildir/')

# 遍历邮件文件夹里的所有邮件
for root, dirs, files in os.walk(mail_folder):
    for filename in files:
        # 构造完整文件路径
        filepath = os.path.join(root, filename)
        # 判断是否为邮件文件
        if os.path.isfile(filepath) and filename.startswith('.'):
            # 打开邮件文件
            with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
                msg = email.message_from_file(f)
                # 遍历邮件附件
                for part in msg.walk():
                    # 判断是否为附件
                    if part.get('Content-Disposition') is not None:
                        filename = part.get_filename()
                        # 判断是否为文本文件
                        if filename.endswith('.txt'):
                            # 读取附件内容
                            content = part.get_payload(decode=True).decode('utf-8')
                            # 提取文件名
                            match = re.search(r'11:(.{10})', content)
                            if match:
                                new_filename = match.group(1) + '.txt'
                                # 构造新文件路径
                                new_filepath = os.path.join(save_path, new_filename)
                                # 保存附件内容
                                with open(new_filepath, 'w', encoding='utf-8', errors='ignore') as f:
                                    f.write(content)

以上代码会遍历指定邮件文件夹里的所有邮件,提取所有附件,如果附件是文本文件并且附件内容里包含字符'11:' 后面的 10 个字符,就以这 10 个字符作为新文件名,并将附件内容保存为 TXT 文件格式在电脑桌面上。

Python 邮件附件处理:提取字符生成新文件名并保存

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

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