Skip to content

Instantly share code, notes, and snippets.

@revolunet
Last active September 26, 2015 00:28
Show Gist options
  • Select an option

  • Save revolunet/1009931 to your computer and use it in GitHub Desktop.

Select an option

Save revolunet/1009931 to your computer and use it in GitHub Desktop.
IMAP email addresses grabber
# -*- encoding: UTF-8 -*-
# grab email addresses from your IMAP inbox
def getHeadersFromEmails(host = 'imap.gmail.com', username = '', password = '', folder = 'INBOX', header = 'FROM', search = 'ALL'):
import imaplib
import re
imap = imaplib.IMAP4_SSL(host, 993)
imap.login(username, password)
mboxes = imap.list()
n = imap.select(folder)
print "fetching %s messages" % n[1][0]
uids = imap.search(None, search)
uids = uids[1][0].split(' ')
emails = []
for uid in uids:
print "fetch message %s" % uid
body = imap.fetch(uid,'(BODY[HEADER.FIELDS (%s)])' % header)
text = body[1][0][1]
m = re.search(r"From: ([^\r\n]+)", text)
if m:
m2 = re.search(r"<([^>]+)>", m.group(1))
if m2:
emails.append(m2.group(1))
else:
emails.append(m.group(1))
return set(emails)
if __name__ == '__main__':
EMAIL = '[email protected]'
PASSWORD = 'xxxxxxx'
emails = getHeadersFromEmails(username = EMAIL , password = PASSWORD)
print emails
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment