Skip to content

Instantly share code, notes, and snippets.

@marc-hanheide
Created September 7, 2017 15:01
Show Gist options
  • Select an option

  • Save marc-hanheide/78e979f3ed4f5b45816c8e547226ae77 to your computer and use it in GitHub Desktop.

Select an option

Save marc-hanheide/78e979f3ed4f5b45816c8e547226ae77 to your computer and use it in GitHub Desktop.
imap tests with Python
from imaplib import IMAP4_SSL
from email import message_from_string
from getpass import getpass
from json import dumps
from pprint import pprint
def parse_email(raw_email):
email = message_from_string(raw_email)
# print email.items()
d = {
'date': email['date'],
'from': email['from'],
'to': email['to'],
'cc': email['cc'],
'subject': email['subject'],
'headers': email.items(),
'content': []
}
for part in email.walk():
if part.get_content_type().startswith('text/'):
# print "========= " + part.get_content_type()
e = {
'content_type': part.get_content_type(),
'payload': part.get_payload(decode=True)
}
d['content'].append(e)
# print part.get_payload(decode=True).decode()
pprint(d)
mail = IMAP4_SSL('outlook.office365.com')
mail.login('[email protected]', getpass())
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("INBOX") # connect to inbox.
result, data = mail.search(None, "ALL")
ids = data[0] # data is a list.
id_list = ids.split() # ids is a space separated string
latest_email_id = id_list[-1] # get the latest
for i in id_list:
# fetch the email body (RFC822) for the given ID
result, data = mail.fetch(i, "(RFC822)")
raw_email = data[0][1] # here's the body, which is raw text of the whole email
parse_email(raw_email)
#print dumps(d)
# including headers and alternate payloads
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment