用python 处理某个邮件文件夹里邮件附件下载并提取附件文件内容里字符:11:后面的10个字符 作为附件新文件名并以TXT文件格式保存在电脑桌面
以下是处理邮件附件的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文件格式在电脑桌面上
原文地址: https://www.cveoy.top/t/topic/dGC7 著作权归作者所有。请勿转载和采集!