Skip to content

Instantly share code, notes, and snippets.

@ast
Created November 12, 2015 11:06
Show Gist options
  • Save ast/281ae13cab70ea52cdaf to your computer and use it in GitHub Desktop.
Save ast/281ae13cab70ea52cdaf to your computer and use it in GitHub Desktop.
I had to produce a (text) list of all the mail I had received, in my gmail, from two addresses. Here's how I did it. Adjust it to your taste.
#!/usr/bin/env python
import imaplib
from email.parser import HeaderParser
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('yourmail@gmail.com', 'yourpassword')
mail.select("[Gmail]/All Mail")
# Execute an IMAP search query
status, data = mail.search(None, '(OR (FROM "example1@gmail.com") (FROM "example2@gmail.com"))')
parser = HeaderParser()
for msg in data[0].split():
header = mail.fetch(msg, '(BODY[HEADER])')[1][0][1]
d = parser.parsestr(header)
print("{:<8} {}".format("Date:", d["Date"]))
print("{:<8} {}".format("Subject:", d["Subject"]))
print("{:<8} {}".format("From:", d["From"]))
print("{:<8} {}\n".format("To:", d["To"]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment