-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmessage_content.py
67 lines (40 loc) · 1.24 KB
/
message_content.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python
import logging
import quopri
logger = logging.getLogger(__name__)
def get_message_content(message):
"""
Get message content from an email.
Uses `is_multipart()` and `get_payload()` to recursively call this
function and build the message content from the parts.
Parameters
----------
message : email.message.Message
https://docs.python.org/3.4/library/email.message.html#email.message.Message
Returns
-------
str
Raw content of the message that needs to be decoded.
"""
if not message.is_multipart():
return message.get_payload()
parts = [
get_message_content(payload)
for payload in message.get_payload()
]
return ''.join(parts)
def get_message_text(message):
"""
Get text content from an email message.
Uses `get_message_content()` to get the raw mail content.
Parameters
----------
message : email.message.Message
https://docs.python.org/3.4/library/email.message.html#email.message.Message
"""
logger.debug('Start getting message content.')
raw_content = get_message_content(message)
logger.debug('Decoding message content to bytes.')
content_bytes = quopri.decodestring(raw_content, False)
logger.debug('Decoding message bytes to text.')
return content_bytes.decode('utf-8')