Skip to content

Instantly share code, notes, and snippets.

@r0yfire
Last active August 29, 2015 14:09
Show Gist options
  • Save r0yfire/1fdf401904b62a2d5b4f to your computer and use it in GitHub Desktop.
Save r0yfire/1fdf401904b62a2d5b4f to your computer and use it in GitHub Desktop.
Search your emails for a keyword or string and generate CSV file with frequency by month.
import imaplib
import email
from datetime import datetime
###
### Enter your IMAP server address here
###
mail = imaplib.IMAP4_SSL('mail.example.com')
###
### Enter your email and password here
###
mail.login('[email protected]', 'password')
# Select inbox and search
mail.select('inbox')
res, data = mail.search(None, 'BODY', '"fire alarm"')
# Parse emails
emails = [ mail.fetch(x, "(RFC822)") for x in data[0].split() ]
email_list = [ email.message_from_string(x[1][0][1]) for x in emails ]
# Convert to datetime object
dates = [ datetime.strptime(" ".join(x.get('Date').split(' ')[2:4]), '%b %Y') for x in email_list ]
# Get frequency and save to CSV file.
uniq = {}
uniq_get = uniq.get
for i in dates:
uniq[i] = uniq_get(i, 0) + 1
srted = sorted([(x, uniq[x]) for x in uniq], key=lambda k:k[0])
results = [(x[0].strftime('%b %Y'), x[1]) for x in srted]
fh = open('frequency.csv', 'w')
[ fh.write("%s,%s\n" %(x[0], x[1])) for x in results ]
fh.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment