python / python/cpython

email.message.Message.add_header behavior differs from Message[header]=v

未关闭
#151,454 14 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

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

描述

Bug report

Bug description:

Attempting to copy headers from an existing message to a new (to-be-cleaned copy of the original) message, I iterated over the old message, using something like

for h, v in oldmsg.items():
    newmsg.add_header(h, v)

which works for many of the test-messages in my test Maildir folder, but errors out on certain messages with

    newmsg.add_header(h, v)
    ~~~~~~~~~~~~~~~~~~~~~~^^^^^^
  File "/usr/local/lib/python3.13/email/message.py", line 587, in add_header
    self[_name] = SEMISPACE.join(parts)
                  ~~~~~~~~~~~~~~^^^^^^^
TypeError: sequence item 0: expected str instance, Header found

It appears that elements in msg.items() can produce a mixed-content list containing both (str, str) and (str, Header) elements; but add_header doesn't like receiving a Header object as a value, only str.

If I change it to use the .__setitem__() method function:

for h, v in oldmsg.items():
    newmsg[h] = v

it appears to work fine, appending the header that .items() gave me.

According to the .add_header() documentation, it should behave similar to the .__setitem__() method:

This method is similar to __setitem__() except that additional header parameters can be provided as keyword arguments. _name is the header field to add and _value is the primary value for the header.

The fix would involve making add_header accept the same sorts of Header values as __setitem__, or at least align the output of msg.items() with the types that msg.set_header() accepts. If not aligned, at a bare minimum, the documentation should reflect the difference in accepted value types (str vs Header)

This may also have tie-ins with similar Issues here:

  • #65294
  • #91957
  • #101090

(manifested on 3.13 on OpenBSD, but it's standard-library stuff that would likely manifest on any OS)

CPython versions tested on:

3.13

Operating systems tested on:

Other

Linked PRs
  • gh-151458

贡献指南

打开贡献指南

从这里开始

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

调研方向

先查看关联的 PR gh-151458,然后检查 email/message.py 中 Message.add_header 附近的代码,并将其与 Message.setitem 和 items() 进行比较。复现报告中的 str/Header 混合情况;当行为一致,或已记录所接受的值类型差异时,即算完成。

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

评估

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

把新 issue 发到你的邮箱

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