Skip to content

Instantly share code, notes, and snippets.

Created May 27, 2020 10:02
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Scaffolding for fetching and parsing emails from IMAP
# Author: Riyad Preukschas <>
# License: Mozilla Public License 2.0
# Scaffolding for fetching and parsing emails from IMAP
import imaplib
import email.parser
import email.policy
# connect to server
with imaplib.IMAP4_SSL(IMAP_HOST) as imap:
# login with user name and password
# select mail "folder" to work in'INBOX', readonly=True)
# list ALL mails in folder ... can also be used to filter mails
# see
typ, data =, '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(
# do your stuff here ...
# for access to specific parts of the email message
# see
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')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment