Last active
July 17, 2019 03:36
-
-
Save pai911/3d4b19ca1fc817aacbd32c0dd8bd97d7 to your computer and use it in GitHub Desktop.
A util to read an email file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import email | |
from email.header import decode_header | |
# http://imsardine.simplbug.com/note/email/python.html | |
class Email(object): | |
def __init__(self, rfc822): | |
self._rfc822 = rfc822 | |
self._message = email.message_from_string(rfc822) | |
def get_rfc822(self): | |
return self._rfc822 | |
def get_subject(self): | |
subject, charset = decode_header(self._message['SUBJECT'])[0] | |
if charset: subject = subject.decode(charset) | |
return subject | |
def _get_text(self, message): | |
for part in message.walk(): # in depth-first traversal order 1 | |
if part.get_content_maintype() == 'text': | |
text = part.get_payload(decode=True).decode(part.get_content_charset()) # 2 | |
return part.get_content_type(), text | |
if part.get_content_type() == 'multipart/alternative': | |
for altpart in reversed(part.get_payload()): # in an order of increasing faithfulness 3 | |
text = self._get_text(altpart) | |
if text is not None: return text | |
continue | |
return None | |
def get_text(self): | |
return self._get_text(self._message) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment