diff --git a/Lib/email/generator.py b/Lib/email/generator.py index ae670c2353c858a..8922bdcd85a2f77 100644 --- a/Lib/email/generator.py +++ b/Lib/email/generator.py @@ -186,8 +186,9 @@ def _write(self, msg): # If we munged the cte, copy the message again and re-fix the CTE. if munge_cte: msg = deepcopy(msg) - msg.replace_header('content-transfer-encoding', munge_cte[0]) msg.replace_header('content-type', munge_cte[1]) + if msg.get('content-transfer-encoding') is not None: + msg.replace_header('content-transfer-encoding', munge_cte[0]) # Write the headers. First we see if the message object wants to # handle that itself. If not, we'll do it generically. meth = getattr(msg, '_write_headers', None) diff --git a/Lib/test/test_email/test_email.py b/Lib/test/test_email/test_email.py index 621754cf753daa2..66154b5863d66fb 100644 --- a/Lib/test/test_email/test_email.py +++ b/Lib/test/test_email/test_email.py @@ -311,6 +311,34 @@ def test_as_string_policy(self): g.flatten(msg) self.assertEqual(fullrepr, s.getvalue()) + def test_nonascii_as_string_without_cte(self): + m = textwrap.dedent("""\ + MIME-Version: 1.0 + Content-Type: multipart/alternative; + boundary="----5F0D91A9C8C24D91AF71E1D7F2F7877E" + + ------5F0D91A9C8C24D91AF71E1D7F2F7877E + Content-type: text/plain; charset=utf-8 + + Test if UTF-8 messages with no Content-Transfer-Encoding set can be as_string'd: + Föö bär + ------5F0D91A9C8C24D91AF71E1D7F2F7877E-- + + """) + msg = email.message_from_string(m) + msg.as_string() + + def test_nonascii_as_string_without_content_type_and_cte(self): + m = textwrap.dedent("""\ + MIME-Version: 1.0 + + Test if UTF-8 messages with no Content-Type nor Content-Transfer-Encoding set can be as_string'd: + Föö bär + + """) + msg = email.message_from_string(m) + msg.as_string() + def test_as_bytes(self): msg = self._msgobj('msg_01.txt') with openfile('msg_01.txt') as fp: diff --git a/Misc/NEWS.d/next/Library/2018-01-25-21-17-32.bpo-27321.AoxcPm.rst b/Misc/NEWS.d/next/Library/2018-01-25-21-17-32.bpo-27321.AoxcPm.rst new file mode 100644 index 000000000000000..849326466e7457d --- /dev/null +++ b/Misc/NEWS.d/next/Library/2018-01-25-21-17-32.bpo-27321.AoxcPm.rst @@ -0,0 +1,2 @@ +Only replace the munged Content-Type-Encoding header when it actually exists +while flattening an email.