python / python/cpython

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

Abierto
#157,254 1 comentario 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

stdlib topic-email type-bug
Lenguaje dominante
Python
Estrellas
77.2k
Forks
35.9k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

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

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza con los puntos de entrada email.message.EmailMessage.set_content() y add_attachment(), y sigue después los manejadores de contenido de texto y bytes utilizados por las reproducciones. Ejecuta los ejemplos proporcionados y las pruebas relacionadas de email; se considera terminado cuando las solicitudes de contenido fallidas conservan el mensaje serializado anterior y se rechazan los valores de CTE de bytes no compatibles.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
backend
Tipo de issue
Error
Dificultad
3/5
Tiempo estimado
1-2 días
Estado de actividad
Estancado
Claridad
Bien especificado
Aptitud para principiantes
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.