python / python/cpython

email ContentManager mutates messages after failed content validation and accepts unknown byte CTE values

未关闭
#157,254 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

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

描述

Bug report

Summary

EmailMessage.set_content() clears existing content before built-in content validation completes. A failing text-content request therefore destroys the original payload. Separately, the bytes content handler accepts arbitrary cte strings and serializes them as Content-Transfer-Encoding, even though the documented API defines a fixed set of permitted values. Together, these behaviors let invalid content requests corrupt an existing message or produce invalid outgoing MIME metadata.

Reproduction Code
from email.message import EmailMessage

# Failed text setup loses the prior message content.
msg = EmailMessage()
msg.set_content("original")
before = msg.as_bytes()
try:
    msg.set_content("replacement", charset="does-not-exist")
except LookupError as exc:
    print(type(exc).__name__, exc)
print(msg.as_bytes() == before)
print(msg.as_string())

# Unsupported byte CTE is accepted and emitted unchanged.
msg = EmailMessage()
msg.set_content(
    b"abc",
    maintype="application",
    subtype="octet-stream",
    cte="not-a-transfer-encoding",
)
print(msg.as_bytes().decode("ascii"))
Actual Behavior

The first request raises LookupError: unknown encoding: does-not-exist, then prints False. The serialized message no longer contains original; it retains MIME headers added before the failure.

The second request succeeds and produces:

Content-Type: application/octet-stream
Content-Transfer-Encoding: not-a-transfer-encoding
MIME-Version: 1.0

abc

A failing add_attachment("replacement", charset="does-not-exist") also leaves the parent converted to a one-part multipart/mixed message.

Expected Behavior

Invalid content requests should raise before changing the target message. In particular, a failed set_content() or add_attachment() call should preserve the prior serialized message and MIME structure.

The bytes content handler should reject unsupported CTE values with ValueError, consistently with the documented CTE set and the text content handler, rather than emitting an unrecognized Content-Transfer-Encoding header.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs
  • gh-157263

贡献指南

打开贡献指南

从这里开始

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

调研方向

从 email.message.EmailMessage.set_content() 和 add_attachment() 入口开始,然后跟踪复现代码使用的文本和 bytes 内容处理器。运行提供的示例和相关的 email 测试;当失败的内容请求保留之前序列化的消息,并拒绝不支持的 bytes CTE 值时,即表示完成。

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

评估

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

把新 issue 发到你的邮箱

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