payload = '--Sorry: cannot decode Unicode text--'
return payload
def findMainText(self, message, asStr=True):
"""
for text-oriented clients, return first text part's str;
for the payload of a simple message, or all parts of
a multipart message, looks for text/plain, then text/html,
then text/*, before deducing that there is no text to
display; this is a heuristic, but covers most simple,
multipart/alternative, and multipart/mixed messages;
content-type defaults to text/plain if not in simple msg;
handles message nesting at top level by walking instead
of list scans; if non-multipart but type is text/html,
returns the HTML as the text with an HTML type: caller
may open in web browser, extract plain text, etc; if
nonmultipart and not text, there is no text to display:
save/open message content in UI; caveat: does not try
to concatenate multiple inline text/plain parts if any;
4E: text payloads may be bytes--decodes to str here;
4E: asStr=False to get raw bytes for HTML file saves;
"""
try to find a plain text
for part in message.walk(): # walk visits message
type = part.get_content_type() # if nonmultipart
if type == 'text/plain': # may be base64,qp,uu
return type, self.decodedPayload(part, asStr) # bytes to str too?
try to find an HTML part
for part in message.walk():
type = part.get_content_type() # caller renders html
if type == 'text/html':
return type, self.decodedPayload(part, asStr)
try any other text type, including XML
for part in message.walk():
if part.get_content_maintype() == 'text':
return part.get_content_type(), self.decodedPayload(part, asStr)
punt: could use first part, but it's not marked as text
failtext = '[No text to display]' if asStr else b'[No text to display]'
return 'text/plain', failtext
def decodeHeader(self, rawheader):
"""
4E: decode existing i18n message header text per both email and Unicode
standards, according to its content; return as is if unencoded or fails;
client must call this to display: parsed Message object does not decode;
i18n header example: '=?UTF-8?Q?Introducing=20Top=20Values=20..Savers?=';
i18n header example: 'Man where did you get that =?UTF-8?Q?assistant=3F?=';
decode_header handles any line breaks in header string automatically, may
return multiple parts if any substrings of hdr are encoded, and returns all
980 | Chapter 13: Client-Side Scripting