Skip to content

Commit c6e3282

Browse files
maxkingmiss-islington
authored andcommitted
[3.8] bpo-33972: Fix EmailMessage.iter_attachments raising AttributeError (GH-14119) (GH-14380)
When certain malformed messages have content-type set to 'mulitpart/*' but still have a single part body, iter_attachments can raise AttributeError. This patch fixes it by returning a None value instead when the body is single part. (cherry picked from commit 0225701) Co-authored-by: Abhilash Raj <[email protected]> https://bugs.python.org/issue33972
1 parent 12d174b commit c6e3282

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

Lib/email/message.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1041,7 +1041,16 @@ def iter_attachments(self):
10411041
maintype, subtype = self.get_content_type().split('/')
10421042
if maintype != 'multipart' or subtype == 'alternative':
10431043
return
1044-
parts = self.get_payload().copy()
1044+
payload = self.get_payload()
1045+
# Certain malformed messages can have content type set to `multipart/*`
1046+
# but still have single part body, in which case payload.copy() can
1047+
# fail with AttributeError.
1048+
try:
1049+
parts = payload.copy()
1050+
except AttributeError:
1051+
# payload is not a list, it is most probably a string.
1052+
return
1053+
10451054
if maintype == 'multipart' and subtype == 'related':
10461055
# For related, we treat everything but the root as an attachment.
10471056
# The root may be indicated by 'start'; if there's no start or we

Lib/test/test_email/test_message.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -929,6 +929,15 @@ def test_set_content_does_not_add_MIME_Version(self):
929929
m.set_content(content_manager=cm)
930930
self.assertNotIn('MIME-Version', m)
931931

932+
def test_string_payload_with_multipart_content_type(self):
933+
msg = message_from_string(textwrap.dedent("""\
934+
Content-Type: multipart/mixed; charset="utf-8"
935+
936+
sample text
937+
"""), policy=policy.default)
938+
attachments = msg.iter_attachments()
939+
self.assertEqual(list(attachments), [])
940+
932941

933942
if __name__ == '__main__':
934943
unittest.main()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Email with single part but content-type set to ``multipart/*`` doesn't raise
2+
AttributeError anymore.

0 commit comments

Comments
 (0)