Skip to content

Commit 6a31bc6

Browse files
committed
#15232: correctly mangle From lines in MIME preamble and epilogue
1 parent e60e12b commit 6a31bc6

3 files changed

Lines changed: 35 additions & 2 deletions

File tree

Lib/email/generator.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,11 @@ def _handle_multipart(self, msg):
233233
msg.set_boundary(boundary)
234234
# If there's a preamble, write it out, with a trailing CRLF
235235
if msg.preamble is not None:
236-
self.write(msg.preamble + self._NL)
236+
if self._mangle_from_:
237+
preamble = fcre.sub('>From ', msg.preamble)
238+
else:
239+
preamble = msg.preamble
240+
self.write(preamble + self._NL)
237241
# dash-boundary transport-padding CRLF
238242
self.write('--' + boundary + self._NL)
239243
# body-part
@@ -251,7 +255,11 @@ def _handle_multipart(self, msg):
251255
self.write(self._NL + '--' + boundary + '--')
252256
if msg.epilogue is not None:
253257
self.write(self._NL)
254-
self.write(msg.epilogue)
258+
if self._mangle_from_:
259+
epilogue = fcre.sub('>From ', msg.epilogue)
260+
else:
261+
epilogue = msg.epilogue
262+
self.write(epilogue)
255263

256264
def _handle_multipart_signed(self, msg):
257265
# The contents of signed parts has to stay unmodified in order to keep

Lib/email/test/test_email.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1275,6 +1275,28 @@ def test_dont_mangle_from(self):
12751275
Blah blah blah
12761276
""")
12771277

1278+
def test_mangle_from_in_preamble_and_epilog(self):
1279+
s = StringIO()
1280+
g = Generator(s, mangle_from_=True)
1281+
msg = email.message_from_string(textwrap.dedent("""\
1282+
From: foo@bar.com
1283+
Mime-Version: 1.0
1284+
Content-Type: multipart/mixed; boundary=XXX
1285+
1286+
From somewhere unknown
1287+
1288+
--XXX
1289+
Content-Type: text/plain
1290+
1291+
foo
1292+
1293+
--XXX--
1294+
1295+
From somewhere unknowable
1296+
"""))
1297+
g.flatten(msg)
1298+
self.assertEqual(len([1 for x in s.getvalue().split('\n')
1299+
if x.startswith('>From ')]), 2)
12781300

12791301

12801302
# Test the basic MIMEAudio class

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,9 @@ Core and Builtins
9898
Library
9999
-------
100100

101+
- Issue #15232: when mangle_from is True, email.Generator now correctly mangles
102+
lines that start with 'From' that occur in a MIME preamble or epilogue.
103+
101104
- Issue #13922: argparse no longer incorrectly strips '--'s that appear
102105
after the first one.
103106

0 commit comments

Comments
 (0)