-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathutils.py
47 lines (40 loc) · 1.86 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Utils(object):
# From https://gist.github.com/miohtama/5389146
@staticmethod
def get_decoded_email_body(msg, html_needed):
""" Decode email body.
Detect character set if the header is not set.
We try to get text/plain, but if there is not one then fallback to text/html.
:param html_needed: html if True, or plain if False, or None perhaps
:param message_body: Raw 7-bit message body input e.g. from imaplib. Double encoded in quoted-printable and latin-1
:return: Message body as unicode string
"""
multipart = msg.is_multipart()
content_type_is_html = msg.get_content_type() == "text/html"
text = ""
if multipart:
html = None
for part in msg.get_payload():
if part.get_content_charset() is None:
# We cannot know the character set, so return decoded "something"
text = part.get_payload(decode=True)
continue
charset = part.get_content_charset()
if part.get_content_type() == 'text/plain' and html_needed == False:
text = part.get_payload(decode=True)
return text.strip()
if part.get_content_type() == 'text/html' and html_needed == True:
html = part.get_payload(decode=True)
return html.strip()
elif not multipart and content_type_is_html:
payload = msg.get_payload(decode=True)
return payload.strip()
else:
if html_needed == False:
chrset = msg.get_content_charset()
if chrset is not None:
return msg.get_payload(decode=True).strip()
else:
return msg.get_payload(decode=True)
else:
return None