def decode_text(message):
"""Extracts the text of the message and try to convert it to utf-8. This method
do not checks if the message is multipart or if the message mime type is plain
text or html. Maybe you want to use the methods :class:`Text.text` and
:class:`Text.html`.
Parameters
----------
message: email.message.Message
Message to extract its text.
Returns
-------
content: str
Text of the message encoded to utf-8. If it cannot encode the text to utf-8
the text will be returned as ascii.
Raises
------
TypeError
If the parameter is not an instance of :class:`email.message.Message`.
"""
def utf8(text):
try:
charset = message.get_content_charset()
if charset:
return text.decode(charset).encode('utf-8')
except LookupError:
return text
except (UnicodeDecodeError, UnicodeEncodeError):
return text
return text
try:
return utf8(Text.decode_content(message))
except (UnicodeDecodeError, UnicodeEncodeError):
return message.get_payload().encode('ascii')
评论列表
文章目录