Skip to content

Instantly share code, notes, and snippets.

@pai911
Last active July 17, 2019 03:36
Show Gist options
  • Save pai911/3d4b19ca1fc817aacbd32c0dd8bd97d7 to your computer and use it in GitHub Desktop.
Save pai911/3d4b19ca1fc817aacbd32c0dd8bd97d7 to your computer and use it in GitHub Desktop.
A util to read an email file
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