如何用Python从带嵌套.msg附件的Outlook邮件中提取邮箱地址
解决方案
核心思路
通过递归解析.msg文件实现嵌套附件的邮箱提取:
- 解析当前邮件的发件人、收件人、抄送人等字段中的邮箱地址
- 遍历邮件所有附件,若附件为.msg格式,则临时保存该附件并递归解析其内容,完成后删除临时文件
依赖安装
首先安装所需库:
pip install extract-msg pandas
修改后的完整代码
import os import uuid import pandas as pd import extract_msg def extract_emails_from_msg(file_path, excluded_email): email_addresses = set() try: # 打开.msg文件 msg = extract_msg.Message(file_path) # 提取发件人邮箱 if msg.senderEmail and msg.senderEmail != excluded_email: email_addresses.add(msg.senderEmail.strip()) # 提取收件人邮箱 if msg.to: for recipient in msg.to.split(';'): email = recipient.strip() if email and email != excluded_email: email_addresses.add(email) # 提取抄送人邮箱 if msg.cc: for recipient in msg.cc.split(';'): email = recipient.strip() if email and email != excluded_email: email_addresses.add(email) # 处理嵌套的.msg附件 for attachment in msg.attachments: # 判断附件是否为.msg文件 if attachment.longFilename and attachment.longFilename.endswith('.msg'): # 生成唯一临时文件名,避免冲突 temp_msg_path = f"temp_{uuid.uuid4()}.msg" # 保存附件到临时文件 attachment.save(customPath=temp_msg_path) # 递归提取临时.msg文件中的邮箱 email_addresses.update(extract_emails_from_msg(temp_msg_path, excluded_email)) # 删除临时文件 os.remove(temp_msg_path) except Exception as e: print(f"处理文件 {file_path} 时出错: {str(e)}") return email_addresses def extract_emails_from_folder(folder_path, excluded_email): email_addresses = set() for filename in os.listdir(folder_path): if filename.endswith('.msg'): file_path = os.path.join(folder_path, filename) email_addresses.update(extract_emails_from_msg(file_path, excluded_email)) df = pd.DataFrame({'Email Addresses': list(email_addresses)}) print(df) # 可选:保存到CSV文件 # df.to_csv('extracted_emails.csv', index=False) # 示例调用 # extract_emails_from_folder('your_folder_path', 'exclude@example.com')
代码说明
extract_emails_from_msg:负责单个.msg文件的解析,包括邮件本身的邮箱提取和嵌套附件的递归处理extract_emails_from_folder:遍历目标文件夹下所有.msg文件,收集所有提取到的邮箱并转为DataFrame输出- 临时文件使用UUID命名,避免同一目录下文件名冲突
- 加入异常捕获,避免单个文件解析失败导致整个程序终止
内容的提问来源于stack exchange,提问作者SS22
相关产品推荐
相关产品推荐

