[Python-checkins] bpo-41402: Fix email ContentManager calling .encode() on bytes (GH-21631) (GH-27687)

ambv webhook-mailer at python.org
Mon Aug 9 18:35:07 EDT 2021


https://github.com/python/cpython/commit/395f4c7fbfb89b8724a4abf84410b5e1e374932d
commit: 395f4c7fbfb89b8724a4abf84410b5e1e374932d
branch: 3.9
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: ambv <lukasz at langa.pl>
date: 2021-08-10T00:34:58+02:00
summary:

bpo-41402: Fix email ContentManager calling .encode() on bytes (GH-21631) (GH-27687)

(cherry picked from commit b33186bc43bb5aaf652dd9d093a08fdde796d499)

Co-authored-by: Johannes Reiff <mail at jreiff.de>

files:
A Misc/NEWS.d/next/Library/2020-07-26-18-17-30.bpo-41402.YRkVkp.rst
M Lib/email/contentmanager.py
M Lib/test/test_email/test_contentmanager.py

diff --git a/Lib/email/contentmanager.py b/Lib/email/contentmanager.py
index b91fb0e5bca7a8..3cf62dc8621cd9 100644
--- a/Lib/email/contentmanager.py
+++ b/Lib/email/contentmanager.py
@@ -238,9 +238,7 @@ def set_bytes_content(msg, data, maintype, subtype, cte='base64',
         data = binascii.b2a_qp(data, istext=False, header=False, quotetabs=True)
         data = data.decode('ascii')
     elif cte == '7bit':
-        # Make sure it really is only ASCII.  The early warning here seems
-        # worth the overhead...if you care write your own content manager :).
-        data.encode('ascii')
+        data = data.decode('ascii')
     elif cte in ('8bit', 'binary'):
         data = data.decode('ascii', 'surrogateescape')
     msg.set_payload(data)
diff --git a/Lib/test/test_email/test_contentmanager.py b/Lib/test/test_email/test_contentmanager.py
index f4f6bb715acdce..694cef4ba7e413 100644
--- a/Lib/test/test_email/test_contentmanager.py
+++ b/Lib/test/test_email/test_contentmanager.py
@@ -776,6 +776,18 @@ def test_set_non_ascii_filename(self):
             foo
             """).encode('ascii'))
 
+    def test_set_content_bytes_cte_7bit(self):
+        m = self._make_message()
+        m.set_content(b'ASCII-only message.\n',
+            maintype='application', subtype='octet-stream', cte='7bit')
+        self.assertEqual(str(m), textwrap.dedent("""\
+            Content-Type: application/octet-stream
+            Content-Transfer-Encoding: 7bit
+            MIME-Version: 1.0
+
+            ASCII-only message.
+            """))
+
     content_object_params = {
         'text_plain': ('content', ()),
         'text_html': ('content', ('html',)),
diff --git a/Misc/NEWS.d/next/Library/2020-07-26-18-17-30.bpo-41402.YRkVkp.rst b/Misc/NEWS.d/next/Library/2020-07-26-18-17-30.bpo-41402.YRkVkp.rst
new file mode 100644
index 00000000000000..45585a469e7247
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2020-07-26-18-17-30.bpo-41402.YRkVkp.rst
@@ -0,0 +1 @@
+Fix :meth:`email.message.EmailMessage.set_content` when called with binary data and ``7bit`` content transfer encoding.



More information about the Python-checkins mailing list