diff -r 61aa76adca20 Lib/email/mime/text.py --- a/Lib/email/mime/text.py Thu Mar 22 10:40:20 2012 -0400 +++ b/Lib/email/mime/text.py Thu Mar 22 13:57:49 2012 -0400 @@ -9,7 +9,6 @@ from email.encoders import encode_7or8bit from email.mime.nonmultipart import MIMENonMultipart - class MIMEText(MIMENonMultipart): """Class for generating text/* type MIME documents.""" @@ -27,4 +26,12 @@ """ MIMENonMultipart.__init__(self, 'text', _subtype, **{'charset': _charset}) + + try: + _text.encode(_charset) + except UnicodeEncodeError: + if _charset!='us-ascii': + raise + _charset = 'utf-8' + self.set_payload(_text, _charset) diff -r 61aa76adca20 Lib/test/test_email/test_email.py --- a/Lib/test/test_email/test_email.py Thu Mar 22 10:40:20 2012 -0400 +++ b/Lib/test/test_email/test_email.py Thu Mar 22 13:57:49 2012 -0400 @@ -617,6 +617,19 @@ abc """)) + def test_unicode_body_defaults_to_utf8_encoding(self): + # Issue 14291 + m = MIMEText('É testabc\n') + self.assertEqual(str(m),textwrap.dedent("""\ + MIME-Version: 1.0 + Content-Type: text/plain; charset="utf-8" + Content-Transfer-Encoding: base64 + + w4kgdGVzdGFiYwo= + """)) + + + # Test the email.encoders module class TestEncoders(unittest.TestCase): @@ -642,7 +655,7 @@ eq(msg['content-transfer-encoding'], '7bit') # Similar, but with 8bit data msg = MIMEText('hello \xf8 world') - eq(msg['content-transfer-encoding'], '8bit') + eq(msg['content-transfer-encoding'], 'base64') # And now with a different charset msg = MIMEText('hello \xf8 world', _charset='iso-8859-1') eq(msg['content-transfer-encoding'], 'quoted-printable') diff -r 61aa76adca20 Lib/test/test_email/torture_test.py --- a/Lib/test/test_email/torture_test.py Thu Mar 22 10:40:20 2012 -0400 +++ b/Lib/test/test_email/torture_test.py Thu Mar 22 13:57:49 2012 -0400 @@ -10,10 +10,10 @@ import os import unittest from io import StringIO -from types import ListType -from email.test.test_email import TestEmailBase -from test.support import TestSkipped, run_unittest +from test.test_email import TestEmailBase +from unittest.case import SkipTest +from test.support import run_unittest import email from email import __file__ as testfile @@ -28,7 +28,7 @@ try: openfile('crispin-torture.txt') except IOError: - raise TestSkipped + raise SkipTest @@ -50,10 +50,10 @@ neq = self.ndiffAssertEqual msg = self._msgobj('crispin-torture.txt') payload = msg.get_payload() - eq(type(payload), ListType) + eq(type(payload), list) eq(len(payload), 12) - eq(msg.preamble, None) - eq(msg.epilogue, '\n') + eq(msg.preamble, '') + eq(msg.epilogue, '') # Probably the best way to verify the message is parsed correctly is to # dump its structure and compare it against the known structure. fp = StringIO()