
本文详解如何使用 Python 的 email 模块安全、准确地提取 IMAP 收取邮件的正文内容,重点解决 get_payload() 返回嵌套对象而非可读字符串的问题,并推荐现代写法(message_from_bytes + get_body)。
本文详解如何使用 python 的 `email` 模块安全、准确地提取 imap 收取邮件的正文内容,重点解决 `get_payload()` 返回嵌套对象而非可读字符串的问题,并推荐现代写法(`message_from_bytes` + `get_body`)。
在通过 IMAP 协议(如 imaplib)获取邮件后,许多开发者会误用 email.message_from_string() 处理原始字节流,或直接调用 get_payload() 而未考虑 MIME 结构,导致返回 Message 对象列表而非实际文本。根本原因在于:现代邮件多为 multipart(如 multipart/alternative),正文可能包含纯文本(text/plain)、HTML(text/html)甚至嵌套附件部分,需按标准 MIME 规则解析。
✅ 推荐做法:使用 message_from_bytes + get_body()
Python 3.3+ 引入了更健壮的 email.policy 机制,默认启用 EmailMessage 类(取代老旧的 Message),其 get_body() 方法可智能定位首选正文部分:
import imaplib
import email
from email.policy import default
def read_email_body(username: str, password: str, sender_of_interest: str = None) -> list:
imap = imaplib.IMAP4_SSL("imap.mail.com", 993)
imap.login(username, password)
imap.select('INBOX')
# 搜索未读邮件
search_criteria = ['UNSEEN']
if sender_of_interest:
search_criteria.extend(['FROM', sender_of_interest])
status, response = imap.uid('SEARCH', None, *search_criteria)
if status != 'OK':
return []
msg_ids = response[0].split()
results = []
for e_id in msg_ids:
# 直接 fetch RFC822 原始字节(非字符串!)
_, response = imap.uid('FETCH', e_id, '(RFC822)')
raw_email_bytes = response[0][1] # type: bytes
# 使用 message_from_bytes + policy=default 解析
msg = email.message_from_bytes(raw_email_bytes, policy=default)
# 获取首选正文:优先 HTML,其次 text/plain
body_part = msg.get_body(preferencelist=('html', 'text'))
body_text = body_part.get_content() if body_part else ''
results.append({
'from': email.utils.parseaddr(msg.get('From', '')),
'to': msg.get('To', ''),
'subject': msg.get('Subject', ''),
'body': body_text.strip()
})
imap.logout()
return results⚠️ 关键注意事项
- 绝不要对原始响应字节调用 .decode('utf-8') 后再用 message_from_string():IMAP 返回的 RFC822 内容是二进制流,可能含非 UTF-8 编码(如 ISO-8859-1 或 base64 编码的 payload),强制解码会引发 UnicodeDecodeError 或损坏数据。
- get_body() 的 preferencelist 参数决定内容优先级:('html', 'text') 表示先找 text/html,找不到则回退到 text/plain;若只需纯文本,可设为 ('text',)。
- 处理异常结构:若 get_body() 返回 None(如邮件仅有附件无正文)或返回 multipart/alternative(罕见但可能),需手动遍历 msg.iter_parts() 并检查 part.get_content_maintype() 和 part.get_content_subtype()。
- 编码兼容性:get_content() 内部已自动处理 Content-Transfer-Encoding(如 base64, quoted-printable),无需额外调用 base64.b64decode()。
? 验证与调试技巧
若仍遇到空正文,可在解析后添加诊断逻辑:
# 调试:打印邮件结构概览
print(f"Content-Type: {msg.get_content_type()}")
print(f"Is multipart: {msg.is_multipart()}")
if msg.is_multipart():
for i, part in enumerate(msg.iter_parts()):
print(f" Part {i}: {part.get_content_type()} | "
f"Encoding: {part.get('Content-Transfer-Encoding', 'n/a')}")✅ 总结
提取邮件正文不是简单的 .get_payload() 调用,而是遵循 MIME 标准的结构化解析过程。坚持以下三原则即可稳定获取文本:
立即学习“前端免费学习笔记(深入)”;
- 始终用 message_from_bytes() 处理 IMAP 原始响应;
- 优先使用 get_body(preferencelist=...) 定位正文部分;
- 依赖 get_content() 自动解码,避免手动 base64/quoted-printable 处理。
此方法兼容主流邮箱(Gmail、Outlook、Mail.com)发送的现代邮件格式,兼顾鲁棒性与可维护性。











