Skip to content

Instantly share code, notes, and snippets.

@dsiganos
Created March 29, 2018 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsiganos/a0468b52793cc11e39fe327e09aa238c to your computer and use it in GitHub Desktop.
Save dsiganos/a0468b52793cc11e39fe327e09aa238c to your computer and use it in GitHub Desktop.
Access gmail and process emails from python
#!/usr/bin/python
#
# https://yuji.wordpress.com/2011/06/22/python-imaplib-imap-example-with-gmail
#
# To access gmail emails you must setup two factor authentication and then
# create an application specific password to the email bypassing the
# two factor authentication.
import imaplib
import email
import sys
def list_mail_folders():
for i in mail.list()[1]:
print i
def process_email(emails, em, matchstr):
if matchstr in em:
tokens = em.replace('>', '<').split('<')
if len(tokens) > 0:
line = ''
for i in tokens:
line += i.strip()
emails[line] = emails.get(line, 0)
emails[line] += 1
def process_list_of_emails(emails, field, matchstr):
for i in field.split(','):
if matchstr in i:
process_email(emails, i, matchstr)
emails = {}
username = sys.argv[1]
password = sys.argv[2]
matchstr = sys.argv[3]
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(username, password)
list_mail_folders()
mail.select("[Gmail]/All Mail")
#mail.select("inbox")
result, data = mail.search(None, "ALL")
id_list = data[0].split() # ids is a space separated string
print id_list
for i in id_list:
result, data = mail.fetch(i, "(RFC822)")
raw_email = data[0][1]
e = email.message_from_string(raw_email)
to = e.get('To', None)
frm = e.get('From', None)
cc = e.get('Cc', None)
if frm and matchstr in frm:
process_list_of_emails(emails, frm, matchstr)
if cc and matchstr in cc:
process_list_of_emails(emails, cc, matchstr)
if to and matchstr in to:
process_list_of_emails(emails, to, matchstr)
for i in emails.keys():
print i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment