如何解码谷歌邮箱中邮件的MIME编码内容?
解决IMAPClient获取邮件的编码解码问题
主题解码(Quoted-Printable编码)
你看到的主题b'=?UTF-8?Q?The_Morning:_Peru=E2=80=99s_deadly_protests?='是MIME Quoted-Printable(QP)编码格式,Python标准库的email.header模块就能直接解码,无需额外安装第三方库,速度也有保障。
示例代码:
import email.header encoded_subject = b'=?UTF-8?Q?The_Morning:_Peru=E2=80=99s_deadly_protests?=' # 解码后返回(解码文本, 编码格式)的元组 decoded_subject, encoding = email.header.decode_header(encoded_subject)[0] # 确保转换为字符串格式 if isinstance(decoded_subject, bytes): decoded_subject = decoded_subject.decode(encoding) print(decoded_subject) # 输出: The Morning: Peru’s deadly protests
正文编码处理
正文里的=换行、=3D、=0D=0A都是QP编码的典型特征:
=开头的换行是QP的软换行,用于拆分长行,解码时会自动移除=3D是=的转义字符,解码后会还原为==0D=0A是Windows风格的换行符(CRLF),解码后可按需保留或替换
用标准库的quopri模块即可处理,结合email模块的Message类解析更省心。
结合你的IMAPClient代码,处理正文的示例:
import imapclient import quopri import email # 假设已完成IMAP连接与登录 client = imapclient.IMAPClient('imap.gmail.com', ssl=True) client.login('your_email@gmail.com', 'your_app_password') client.select_folder('INBOX') messages = client.search(['SUBJECT', 'The Morning']) target_msg_id = messages[-1] # 取最新一封目标邮件 # 获取邮件原始内容 raw_msg = client.fetch(target_msg_id, ['BODY[]'])[target_msg_id][b'BODY[]'] # 解析为email.Message对象 msg = email.message_from_bytes(raw_msg) # 提取并解码正文 if msg.is_multipart(): # 多部分邮件,遍历找到纯文本部分 for part in msg.walk(): if part.get_content_type() == 'text/plain': encoded_body = part.get_payload(decode=False) decoded_body = quopri.decodestring(encoded_body).decode('utf-8') # 按需替换换行格式 decoded_body = decoded_body.replace('\r\n', '\n') print(decoded_body) else: # 单部分邮件直接解码 encoded_body = msg.get_payload(decode=False) decoded_body = quopri.decodestring(encoded_body).decode('utf-8') decoded_body = decoded_body.replace('\r\n', '\n') print(decoded_body)
为什么推荐标准库?
你提到red box和imap_tools速度偏慢,而Python标准库的email和quopri都是底层轻量实现,和IMAPClient配合完全不会拖慢速度,无需额外依赖,稳定性也更可靠。
内容的提问来源于stack exchange,提问作者Peter Moore
相关产品推荐
相关产品推荐

