message_from_string return msg with wrong encode
還沒有人認領這個 Issue。
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 36k
- 平均合併
- 1 天 9 小時
- 30 天內合併 PR
- 558
描述
Bug report

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.

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")
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 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