Skip to content

Instantly share code, notes, and snippets.

@rhefner1
Last active September 22, 2016 19:10
Show Gist options
  • Save rhefner1/cdf5b1c58a021b231b069ec3e2906f79 to your computer and use it in GitHub Desktop.
Save rhefner1/cdf5b1c58a021b231b069ec3e2906f79 to your computer and use it in GitHub Desktop.
import csv
import email
import getpass
import imaplib
EMAIL_SERVER = 'imap.gmail.com'
def split_addresses(addr_list):
# split an address list into list of tuples of (name,address)
if not addr_list:
return []
out_q = True
cut = -1
res = []
for i in range(len(addr_list)):
if addr_list[i] == '"':
out_q = not out_q
if out_q and addr_list[i] == ',':
res.append(email.utils.parseaddr(addr_list[cut + 1:i]))
cut = i
res.append(email.utils.parseaddr(addr_list[cut + 1:i + 1]))
return res
def authenticate_to_gmail(username):
mail = imaplib.IMAP4_SSL(EMAIL_SERVER)
password = getpass.getpass()
mail.login(username, password)
mail.select("INBOX")
return mail
def get_messages(username):
mail = authenticate_to_gmail(username)
result, data = mail.search(None, "ALL")
message_ids = data[0].split()
return mail.fetch(','.join(message_ids), '(BODY.PEEK[HEADER])')[1][0::2]
def main():
username = raw_input("Username: ")
messages = get_messages(username)
with open('emails.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(['Name', 'Email'])
for msg in (email.message_from_string(raw_msg) for _, raw_msg in messages):
if 'to' in msg:
if username in msg['to']:
for addr in split_addresses(msg['from']):
writer.writerow(list(addr))
if 'from' in msg:
if msg['from'] == username:
for addr in split_addresses(msg['to']):
writer.writerow(list(addr))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment