python / python/cpython

message_from_string return msg with wrong encode

オープン
#94,600 コメント 2 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

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. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、レポートでリンクされている get_payload の実装周辺にある Lib/email/message.py から始め、提供されたスクリプトと添付ファイル TextBased.txt を使って動作を再現します。get_payload(decode=True) と、get_charsets() で取得したパートの宣言済み charset を比較します。text/plain のペイロードが宣言済みの charset と整合するエンコーディングで返され、関連する email テストにリグレッションテストのカバレッジが追加されれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
backend
issue の種類
バグ
難易度
3/5
見積もり時間
1〜2日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
45/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。