Fix: For badly formatted messages use MIMEText (#1800)

Co-authored-by: Adrià Casajús <adria.casajus@proton.ch>
This commit is contained in:
Adrià Casajús 2023-07-11 16:23:37 +02:00 committed by GitHub
parent 516072fd99
commit cb900ed057
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 36 additions and 1 deletions

View File

@ -959,7 +959,14 @@ def add_header(msg: Message, text_header, html_header=None) -> Message:
elif content_type in ("multipart/mixed", "multipart/signed"):
new_parts = []
parts = list(msg.get_payload())
payload = msg.get_payload()
if isinstance(payload, str):
# The message is badly formatted inject as new
new_parts = [MIMEText(text_header, "plain"), MIMEText(payload, "plain")]
clone_msg = copy(msg)
clone_msg.set_payload(new_parts)
return clone_msg
parts = list(payload)
LOG.d("only add header for the first part for %s", content_type)
for ix, part in enumerate(parts):
if ix == 0:

View File

@ -0,0 +1,21 @@
Sender: somebody@somewhere.net
Content-Type: multipart/mixed; boundary="----=_Part_3946_1099248058.1688752298149"
--0c916c9b5fe3c925d7bafeb988bb6794
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable
notification test
--0c916c9b5fe3c925d7bafeb988bb6794
Content-Type: text/html; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable
<html><head><meta http-equiv=3D"Content-Type" content=3D"text/html; charset=
=3DUTF-8"><meta http-equiv=3D"X-UA-Compatible" content=3D"IE=3Dedge"><meta =
name=3D"format-detection" content=3D"telephone=3Dno"><meta name=3D"viewport=
" content=3D"width=3Ddevice-width, initial-scale=3D1.0">
--0c916c9b5fe3c925d7bafeb988bb6794--

View File

@ -822,3 +822,10 @@ def test_sl_formataddr():
# test that the same name-address can't be handled by the built-in formataddr
with pytest.raises(UnicodeEncodeError):
formataddr(("é", "è@ç.à"))
def test_add_header_to_invalid_multipart():
msg = load_eml_file("add_header_multipart.eml")
msg = add_header(msg, "test", "test")
data = msg.as_string()
assert data != ""