#15232: correctly mangle From lines in MIME preamble and epilogue
diff --git a/Lib/email/generator.py b/Lib/email/generator.py
index eb71044..5626ab9 100644
--- a/Lib/email/generator.py
+++ b/Lib/email/generator.py
@@ -212,7 +212,11 @@
             msg.set_boundary(boundary)
         # If there's a preamble, write it out, with a trailing CRLF
         if msg.preamble is not None:
-            print >> self._fp, msg.preamble
+            if self._mangle_from_:
+                preamble = fcre.sub('>From ', msg.preamble)
+            else:
+                preamble = msg.preamble
+            print >> self._fp, preamble
         # dash-boundary transport-padding CRLF
         print >> self._fp, '--' + boundary
         # body-part
@@ -230,7 +234,11 @@
         self._fp.write('\n--' + boundary + '--')
         if msg.epilogue is not None:
             print >> self._fp
-            self._fp.write(msg.epilogue)
+            if self._mangle_from_:
+                epilogue = fcre.sub('>From ', msg.epilogue)
+            else:
+                epilogue = msg.epilogue
+            self._fp.write(epilogue)
 
     def _handle_multipart_signed(self, msg):
         # The contents of signed parts has to stay unmodified in order to keep
diff --git a/Lib/email/test/test_email.py b/Lib/email/test/test_email.py
index 3bb3446..b32da9d 100644
--- a/Lib/email/test/test_email.py
+++ b/Lib/email/test/test_email.py
@@ -9,6 +9,7 @@
 import difflib
 import unittest
 import warnings
+import textwrap
 from cStringIO import StringIO
 
 import email
@@ -948,6 +949,28 @@
 Blah blah blah
 """)
 
+    def test_mangle_from_in_preamble_and_epilog(self):
+        s = StringIO()
+        g = Generator(s, mangle_from_=True)
+        msg = email.message_from_string(textwrap.dedent("""\
+            From: foo@bar.com
+            Mime-Version: 1.0
+            Content-Type: multipart/mixed; boundary=XXX
+
+            From somewhere unknown
+
+            --XXX
+            Content-Type: text/plain
+
+            foo
+
+            --XXX--
+
+            From somewhere unknowable
+            """))
+        g.flatten(msg)
+        self.assertEqual(len([1 for x in s.getvalue().split('\n')
+                                  if x.startswith('>From ')]), 2)
 
 
 # Test the basic MIMEAudio class
diff --git a/Misc/NEWS b/Misc/NEWS
index b73bf0a..16f0a68 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -90,6 +90,9 @@
 Library
 -------
 
+- Issue #15232: when mangle_from is True, email.Generator now correctly mangles
+  lines that start with 'From' that occur in a MIME preamble or epilog.
+
 - Issue #13922: argparse no longer incorrectly strips '--'s that appear
   after the first one.