python / python/cpython

message_from_string return msg with wrong encode

未关闭
#94,600 2 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

topic-email type-bug
主要语言
Python
星标
77.2k
派生
36k
PR 合并指标
PR 指标待抓取

描述

Bug report

image
The text contain non ascii chars. The content of text/plain should show as above. While use email.message_from_string to parse the mime, message.get_payload(decode=True) decode "text/plain" part return wrong encode message.

Debug the code, found here https://github.com/python/cpython/blob/3.10/Lib/email/message.py#L278, get_payload return payload.encode('raw-unicode-escape'), but when I use message.get_charsets() it return utf-8, it doesn't match the encode charset. So the result is wrong. The final result is below, the charset is wrong, then I can't get the correct message.

image

Your environment
Python 3.9.10, macOS Catalina, version 10.15.5

Test code is below.
Runing command: python3 t.py TextBased.eml

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import sys
import email

def get_all_block(message, block_type = "text/plain"):
    content_type = message.get_content_type()
    main_type = message.get_content_maintype()
    if main_type == "multipart":
        if message.is_multipart():
            block = None
            for part in message.get_payload():
                result = get_all_block(part, block_type)
                if result:
                    if block is None:
                        block = result
                    else:
                        block += result
            return block
        else:
            return None
    elif content_type == block_type:
        result = message.get_payload(decode=True)
        if result is not None:
            charsets = message.get_charsets()
            print('charsets', charsets, result)
        return result
    else:
        return None

if __name__ == '__main__':
    fname = sys.argv[1]
    fp = open(fname, 'rb')
    mime = fp.read().decode('utf-8', errors='ignore')
    message = email.message_from_string(mime)
    text = get_all_block(message, "text/plain")

TextBased.txt

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

先从报告中链接的 Lib/email/message.py 里的 get_payload 实现附近开始,然后使用提供的脚本和附件 TextBased.txt 重现该行为。将 get_payload(decode=True) 与通过 get_charsets() 获取的该部分声明的 charset 进行比较。当 text/plain payload 返回的编码与其声明的 charset 一致,并且已在相关的 email 测试中添加回归覆盖时,即视为完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
backend
Issue 类型
缺陷
难度
3/5
预计耗时
1-2 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
45/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。