Skip to content

The agent that grows with you

fix(email): never let unknown or malformed charsets abort the IMAP fetch

Teknium65f407184dea
diff --git a/plugins/platforms/email/adapter.py b/plugins/platforms/email/adapter.py
index f224202b0c5..8698dc93803 100644
--- a/plugins/platforms/email/adapter.py
+++ b/plugins/platforms/email/adapter.py
@@ -216,13 +216,56 @@ def check_email_requirements() -> bool:
return all([addr, pwd, imap, smtp])
+_CHARSET_ALIASES = {
+ # Aliases seen in the wild that Python's codec registry doesn't know.
+ # "unknown-8bit" / "x-unknown" are RFC 1428 placeholders some MTAs (QQ
+ # Mail among them) emit when the original charset was lost (#35901).
+ "unknown-8bit": "utf-8",
+ "unknown": "utf-8",
+ "x-unknown": "utf-8",
+ "default": "utf-8",
+ "ansi_x3.110-1983": "latin-1",
+ "cp-850": "cp850",
+ "gb2312": "gb18030", # superset; avoids failures on GBK extensions
+ "gbk": "gb18030",
+ "ks_c_5601-1987": "cp949",
+}
+
+
+def _safe_decode(payload: bytes, charset: "Optional[str]") -> str:
+ """Decode *payload* without ever raising.
+
+ Unknown or malformed charset labels (``unknown-8bit``, misspelled names,
+ attacker-controlled garbage) previously raised ``LookupError`` from
+ ``bytes.decode`` — ``errors="replace"`` only guards decode errors, not a
+ missing codec — which aborted the whole IMAP fetch and dropped every
+ message in the batch (#35901, #55381, #55383). Fall back through a small
+ alias table, then UTF-8, then latin-1 (which never fails).
+ """
+ label = (charset or "utf-8").strip().strip("\"'").lower() or "utf-8"
+ label = _CHARSET_ALIASES.get(label, label)
+ for candidate in (label, "utf-8"):
+ try:
+ return payload.decode(candidate, errors="replace")
+ except (LookupError, ValueError):
+ continue
+ return payload.decode("latin-1", errors="replace")
+
+
def _decode_header_value(raw: str) -> str:
- """Decode an RFC 2047 encoded email header into a plain string."""
- parts = decode_header(raw)
+ """Decode an RFC 2047 encoded email header into a plain string.
+
+ Never raises: malformed encoded-words or unknown charsets degrade to
+ replacement characters instead of crashing the fetch loop (#55381).
+ """
+ try:
+ parts = decode_header(raw)
+ except Exception: # malformed RFC 2047 structure
+ return raw
decoded = []
for part, charset in parts:
if isinstance(part, bytes):
- decoded.append(part.decode(charset or "utf-8", errors="replace"))
+ decoded.append(_safe_decode(part, charset))
else:
decoded.append(part)
return " ".join(decoded)
@@ -240,8 +283,7 @@ def _extract_text_body(msg: email_lib.message.Message) -> str:
if content_type == "text/plain":
payload = part.get_payload(decode=True)
if payload:
- charset = part.get_content_charset() or "utf-8"
- return payload.decode(charset, errors="replace")
+ return _safe_decode(payload, part.get_content_charset())
# Fallback: try text/html and strip tags
for part in msg.walk():
content_type = part.get_content_type()
@@ -251,15 +293,13 @@ def _extract_text_body(msg: email_lib.message.Message) -> str:
if content_type == "text/html":
payload = part.get_payload(decode=True)
if payload:
- charset = part.get_content_charset() or "utf-8"
- html = payload.decode(charset, errors="replace")
+ html = _safe_decode(payload, part.get_content_charset())
return _strip_html(html)
return ""
else:
payload = msg.get_payload(decode=True)
if payload:
- charset = msg.get_content_charset() or "utf-8"
- text = payload.decode(charset, errors="replace")
+ text = _safe_decode(payload, msg.get_content_charset())
if msg.get_content_type() == "text/html":
return _strip_html(text)
return text
diff --git a/tests/gateway/test_email_charset_fallback.py b/tests/gateway/test_email_charset_fallback.py
new file mode 100644
index 00000000000..2f96d21c63f
--- /dev/null
+++ b/tests/gateway/test_email_charset_fallback.py
@@ -0,0 +1,103 @@
+"""Email charset robustness: unknown/malformed charsets must never drop mail.
+
+Regression tests for #35901 (QQ Mail ``unknown-8bit`` charset raising
+``LookupError`` and aborting the IMAP fetch), #55381 (malformed RFC 2047
+header crashing ``_decode_header_value``), and #55383 (unknown Content-Type
+charset crashing ``_extract_text_body``). UIDs are marked seen before the
+fetch, so any exception in per-message decoding permanently loses messages —
+decoding must degrade, never raise.
+"""
+
+import email as email_lib
+from email.message import EmailMessage
+
+from plugins.platforms.email.adapter import (
+ _decode_header_value,
+ _extract_text_body,
+ _safe_decode,
+)
+
+
+class TestSafeDecode:
+ def test_unknown_8bit_charset_falls_back(self):
+ # QQ Mail emits the RFC 1428 "unknown-8bit" placeholder (#35901).
+ assert _safe_decode("你好".encode("utf-8"), "unknown-8bit") == "你好"
+
+ def test_garbage_charset_label_never_raises(self):
+ assert _safe_decode(b"Hello", "charset") == "Hello"
+ assert _safe_decode(b"Hello", "not-a-codec-!!") == "Hello"
+
+ def test_none_charset_defaults_to_utf8(self):
+ assert _safe_decode("héllo".encode("utf-8"), None) == "héllo"
+
+ def test_gb2312_label_decodes_gbk_extensions(self):
+ # gb2312-labelled mail routinely contains GBK-only characters.
+ assert _safe_decode("镕".encode("gb18030"), "gb2312") == "镕"
+
+ def test_invalid_bytes_replace_not_raise(self):
+ out = _safe_decode(b"ok \xff\xfe bad", "utf-8")
+ assert "ok" in out and "bad" in out
+
+ def test_latin1_last_resort(self):
+ # A charset whose codec exists but whose bytes are invalid UTF-8
+ # still returns text via errors="replace" — never an exception.
+ assert _safe_decode(b"\x96\x97", "unknown-8bit") != ""
+
+
+class TestDecodeHeaderValue:
+ def test_unknown_8bit_encoded_word(self):
+ assert _decode_header_value("=?unknown-8bit?B?SGVsbG8=?=") == "Hello"
+
+ def test_malformed_charset_in_encoded_word(self):
+ # decode_header parses this fine but "charset" is not a codec —
+ # previously a LookupError aborted the whole fetch batch (#55381).
+ out = _decode_header_value("=?charset?B?SGVsbG8=?=")
+ assert isinstance(out, str)
+ assert out # degrades, never raises/empties
+
+ def test_plain_header_passthrough(self):
+ assert _decode_header_value("Just a subject") == "Just a subject"
+
+ def test_qq_mail_gbk_subject(self):
+ # =?gbk?B?...?= with GBK bytes; gbk→gb18030 alias covers extensions.
+ import base64
+ encoded = base64.b64encode("你好".encode("gbk")).decode()
+ assert _decode_header_value(f"=?gbk?B?{encoded}?=") == "你好"
+
+
+class TestExtractTextBodyCharsets:
+ def _msg(self, body_bytes: bytes, charset_label: str):
+ raw = (
+ b"From: [email protected]\r\n"
+ b"Subject: t\r\n"
+ b"MIME-Version: 1.0\r\n"
+ b'Content-Type: text/plain; charset="' + charset_label.encode() + b'"\r\n'
+ b"Content-Transfer-Encoding: 8bit\r\n"
+ b"\r\n" + body_bytes
+ )
+ return email_lib.message_from_bytes(raw)
+
+ def test_unknown_charset_body_does_not_raise(self):
+ # LookupError from an unknown Content-Type charset aborted the
+ # fetch and dropped the message (#55383).
+ msg = self._msg("正文内容".encode("utf-8"), "unknown-8bit")
+ assert "正文内容" in _extract_text_body(msg)
+
+ def test_bogus_charset_body_does_not_raise(self):
+ msg = self._msg(b"plain ascii body", "x-mac-cyrillic-fake")
+ assert "plain ascii body" in _extract_text_body(msg)
+
+ def test_multipart_unknown_charset_part(self):
+ outer = EmailMessage()
+ outer["From"] = "[email protected]"
+ outer["Subject"] = "t"
+ outer.make_mixed()
+ raw_part = (
+ b'Content-Type: text/plain; charset="unknown-8bit"\r\n'
+ b"Content-Transfer-Encoding: 8bit\r\n"
+ b"\r\n"
+ b"part body here"
+ )
+ part = email_lib.message_from_bytes(raw_part)
+ outer.attach(part)
+ assert "part body here" in _extract_text_body(outer)