diff -r f5be7fc270d1 Lib/email/header.py --- a/Lib/email/header.py Fri Oct 17 01:31:29 2014 -0400 +++ b/Lib/email/header.py Fri Oct 17 12:28:02 2014 +0200 @@ -274,7 +274,7 @@ # Now we have to be sure the unicode string can be converted # to a byte string with a reasonable output codec. We want to # use the byte string in the chunk. - for charset in USASCII, charset, UTF8: + for charset in charset, USASCII, UTF8: try: outcodec = charset.output_codec or 'us-ascii' s = s.encode(outcodec, errors) diff -r f5be7fc270d1 Lib/email/test/test_email.py --- a/Lib/email/test/test_email.py Fri Oct 17 01:31:29 2014 -0400 +++ b/Lib/email/test/test_email.py Fri Oct 17 12:28:02 2014 +0200 @@ -3229,6 +3229,18 @@ self.assertEqual(res, '=?iso-8859-2?q?abc?=') self.assertIsInstance(res, str) + def test_encode_with_newlines(self): + res = Header('two\r\nlines','utf-8').encode() + self.assertEqual(res, '=?utf-8?q?two=0D=0Alines?=') + + def test_encode_unicode_with_newlines(self): + res = Header(u'two\r\nlines and \xe0','utf-8').encode() + self.assertEqual(res, '=?utf-8?b?dHdvDQpsaW5lcyBhbmQgw6A=?=') + + def test_encode_unicode_with_newlines_and_only_ascii_chars(self): + res = Header(u'two\r\nlines','utf-8').encode() + self.assertEqual(res, '=?utf-8?q?two=0D=0Alines?=') + # Test RFC 2231 header parameters (en/de)coding class TestRFC2231(TestEmailBase): def test_get_param(self):