daily pastebin goal
47%
SHARE
TWEET

Untitled

a guest Sep 22nd, 2016 81 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import csv
  2. import email
  3. import getpass
  4. import imaplib
  5.  
  6. EMAIL_SERVER = 'imap.gmail.com'
  7.  
  8.  
  9. def split_addresses(addr_list):
  10.     # split an address list into list of tuples of (name,address)
  11.     if not addr_list:
  12.         return []
  13.     out_q = True
  14.     cut = -1
  15.     res = []
  16.     for i in range(len(addr_list)):
  17.         if addr_list[i] == '"':
  18.             out_q = not out_q
  19.         if out_q and addr_list[i] == ',':
  20.             res.append(email.utils.parseaddr(addr_list[cut + 1:i]))
  21.             cut = i
  22.     res.append(email.utils.parseaddr(addr_list[cut + 1:i + 1]))
  23.     return res
  24.  
  25.  
  26. def authenticate_to_gmail(username):
  27.     mail = imaplib.IMAP4_SSL(EMAIL_SERVER)
  28.     password = getpass.getpass()
  29.     mail.login(username, password)
  30.     mail.select("INBOX")
  31.     return mail
  32.  
  33.  
  34. def get_messages(username):
  35.     mail = authenticate_to_gmail(username)
  36.     result, data = mail.search(None, "ALL")
  37.     message_ids = data[0].split()
  38.     return mail.fetch(','.join(message_ids), '(BODY.PEEK[HEADER])')[1][0::2]
  39.  
  40.  
  41. def main():
  42.     username = raw_input("Username: ")
  43.     messages = get_messages(username)
  44.  
  45.     with open('emails.csv', 'w') as f:
  46.         writer = csv.writer(f)
  47.         writer.writerow(['Name', 'Email'])
  48.  
  49.         for msg in (email.message_from_string(raw_msg) for _, raw_msg in messages):
  50.             if 'to' in msg:
  51.                 if username in msg['to']:
  52.                     for addr in split_addresses(msg['from']):
  53.                         writer.writerow(list(addr))
  54.  
  55.             if 'from' in msg:
  56.                 if msg['from'] == username:
  57.                     for addr in split_addresses(msg['to']):
  58.                         writer.writerow(list(addr))
  59.  
  60.  
  61. if __name__ == "__main__":
  62.     main()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top