diff options
author | R David Murray <rdmurray@bitdance.com> | 2013-12-11 21:34:34 (GMT) |
---|---|---|
committer | R David Murray <rdmurray@bitdance.com> | 2013-12-11 21:34:34 (GMT) |
commit | d5c4c7411af644fe7607695eb58ef91fd29066c3 (patch) | |
tree | 725b1c22ba6f5acf3cf5a9b7cdfb39e652b2606a /Lib/email/message.py | |
parent | 31a655411a79b00517cdcd0a2752824d183db792 (diff) | |
download | cpython-d5c4c7411af644fe7607695eb58ef91fd29066c3.zip cpython-d5c4c7411af644fe7607695eb58ef91fd29066c3.tar.gz cpython-d5c4c7411af644fe7607695eb58ef91fd29066c3.tar.bz2 |
#19063: partially fix set_payload handling of non-ASCII string input.
This is a backward compatible partial fix, the complete fix requires raising
an error instead of accepting the invalid input, so the real fix is only
suitable for 3.4.
Diffstat (limited to 'Lib/email/message.py')
-rw-r--r-- | Lib/email/message.py | 26 |
1 files changed, 22 insertions, 4 deletions
diff --git a/Lib/email/message.py b/Lib/email/message.py index f43a380..63b51f6 100644 --- a/Lib/email/message.py +++ b/Lib/email/message.py @@ -275,9 +275,19 @@ class Message: Optional charset sets the message's default character set. See set_charset() for details. """ - if isinstance(payload, bytes): - payload = payload.decode('ascii', 'surrogateescape') - self._payload = payload + if hasattr(payload, 'encode'): + if charset is None: + # We should check for ASCII-only here, but we can't do that + # for backward compatibility reasons. Fixed in 3.4. + self._payload = payload + return + if not isinstance(charset, Charset): + charset = Charset(charset) + payload = payload.encode(charset.output_charset) + if hasattr(payload, 'decode'): + self._payload = payload.decode('ascii', 'surrogateescape') + else: + self._payload = payload if charset is not None: self.set_charset(charset) @@ -316,7 +326,15 @@ class Message: try: cte(self) except TypeError: - self._payload = charset.body_encode(self._payload) + # This if is for backward compatibility and will be removed + # in 3.4 when the ascii check is added to set_payload. + payload = self._payload + if payload: + try: + payload = payload.encode('ascii', 'surrogateescape') + except UnicodeError: + payload = payload.encode(charset.output_charset) + self._payload = charset.body_encode(payload) self.add_header('Content-Transfer-Encoding', cte) def get_charset(self): |