Skip to content

Instantly share code, notes, and snippets.

@riyad
Created May 27, 2020 10:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save riyad/c9a49d43ff0a4dca5ab88b7cdf037d76 to your computer and use it in GitHub Desktop.
Save riyad/c9a49d43ff0a4dca5ab88b7cdf037d76 to your computer and use it in GitHub Desktop.
Scaffolding for fetching and parsing emails from IMAP
#!/usr/bin/python3
#
# Author: Riyad Preukschas <riyad@informatik.uni-bremen.de>
# License: Mozilla Public License 2.0
#
# Scaffolding for fetching and parsing emails from IMAP
import imaplib
import email.parser
import email.policy
IMAP_HOST = ''
IMAP_USER = ''
IMAP_PASSWORD = ''
# connect to server
with imaplib.IMAP4_SSL(IMAP_HOST) as imap:
# login with user name and password
imap.login(IMAP_USER, IMAP_PASSWORD)
# select mail "folder" to work in
imap.select('INBOX', readonly=True)
# list ALL mails in folder ... can also be used to filter mails
# see https://tools.ietf.org/html/rfc2060#section-6.4.4
typ, data = imap.search(None, 'ALL')
message_ids = data[0].split()
for message_id in message_ids:
# fetch "raw" email data
typ, data = imap.fetch(message_id, '(RFC822)')
response_part_rfc822_data = data[0][1]
# create an EmailMessage object from the raw data
msg = email.parser.BytesParser(
policy=email.policy.default).parsebytes(response_part_rfc822_data)
# do your stuff here ...
# for access to specific parts of the email message
# see https://docs.python.org/3/library/email.message.html#email.message.EmailMessage
email_subject = msg['Subject']
email_from = msg['From']
# get email body in plain text form (instead of html)
# ... this might fail, because some mails are HTML-only :/
email_text = msg.get_body('plain').get_content()
print('From : ' + email_from + '\n')
print('Subject : ' + email_subject + '\n')
print(email_text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment