Last active
September 22, 2016 19:10
-
-
Save rhefner1/cdf5b1c58a021b231b069ec3e2906f79 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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