使用Python email库解析message/rfc822附件的精简方案问询
问题根源
现有代码的冗余与稳定性问题来自两点:
- 直接调用
part.as_string()会将整个嵌套邮件的所有MIME结构(包括Content-Type、传输编码头、边界符等非必要信息)全部转为字符串,不符合仅需指定头部和正文的需求。 - 通过
part._payload[0]._headers读取头部属于使用官方email库的私有API,不同Python版本可能出现兼容问题,稳定性差。
优化实现
使用policy.default时,message/rfc822类型的邮件part调用get_payload()会直接返回解析完成的嵌套EmailMessage对象,不需要手动解析或访问私有属性。可按需提取指定头部与正文,自定义拼接为目标文本,完全避免冗余输出。
完整可运行代码
import email from email import policy from email.message import EmailMessage import re def sanitize_filename(name: str) -> str: # 清理文件名中操作系统不允许的非法字符 return re.sub(r'[\\/*?:"<>|]', "_", name) with open("raw_email_message", 'rb') as f: mime_email = email.message_from_binary_file(f, policy=policy.default) for part in mime_email.walk(): content_disposition = str(part.get("Content-Disposition", "")) if "attachment" not in content_disposition: continue content_type = part.get_content_type() if content_type.startswith("message/"): # 直接获取解析完成的嵌套邮件对象,无需访问私有属性 nested_mail: EmailMessage = part.get_payload()[0] # 按需提取需要的标准头部字段,自动处理编码解码 subject = nested_mail.get("Subject", "无主题") sender = nested_mail.get("From", "") receiver = nested_mail.get("To", "") send_date = nested_mail.get("Date", "") # 提取嵌套邮件的纯文本正文,如需HTML可替换为text/html nested_body = "" for nested_part in nested_mail.walk(): if nested_part.get_content_type() == "text/plain" and "attachment" not in str(nested_part.get("Content-Disposition", "")): charset = nested_part.get_content_charset() or "utf-8" nested_body = nested_part.get_payload(decode=True).decode(charset, errors="replace") break # 自定义拼接输出内容,无任何冗余MIME信息 output_content = f"""主题: {subject} 发件人: {sender} 收件人: {receiver} 发送时间: {send_date} --- 正文: {nested_body} """ # 保存为独立文本文件,自动使用主题作为文件名 filename = f"{sanitize_filename(subject)}.txt" with open(filename, "w", encoding="utf-8") as out_f: out_f.write(output_content) else: # 普通非嵌套附件的原有处理逻辑 part_contents = part.get_payload(decode=True) filename = part.get_filename() with open(filename, "wb") as out_f: out_f.write(part_contents)
方案说明
- 全程使用
email库公开API,不访问_payload这类私有属性,兼容Python 3.6及以上官方版本。 - 所有输出内容按需拼接,不会包含多余的MIME头、边界符等冗余信息。
- 正文提取自动识别字符集,避免乱码问题。
- 内置文件名清理逻辑,防止非法字符导致文件保存失败。
- 可根据需求调整提取的头部字段、正文格式(纯文本/HTML),灵活适配不同场景。
内容的提问来源于stack exchange,提问作者kravb
相关产品推荐
相关产品推荐

