Advertisement
Guest User

Untitled

a guest
Oct 27th, 2016
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. import imaplib
  2. import email
  3.  
  4. #Login
  5. mail = imaplib.IMAP4_SSL('imap.gmail.com')
  6. # imaplib module implements connection based on IMAPv4 protocol
  7. mail.login('email', 'pswd')
  8. # >> ('OK', [username at gmail.com Vineet authenticated (Success)'])
  9.  
  10. #Selecting a label
  11.  
  12. mail.list() # Lists all labels in GMail
  13. mail.select('inbox') # Connected to inbox
  14.  
  15. #Searching Through Inbox
  16.  
  17. result, data = mail.search(None, "ALL")
  18. # search and return uids instead
  19. ids = data[0] #data is a list
  20. id_list = ids.split() #ids is a space separated string
  21. i = len(data[0].split())
  22. for x in range(i):
  23. latest_email_id = id_list[x] #get the latest
  24. result, data = result, data = mail.fetch(latest_email_id, "(RFC822)") # fetch the email body (RFC822) for the given ID
  25. raw_email = data[0][1] # here's the body, which is raw text of the whole email
  26.  
  27. #Parsing raw email
  28. print("loop")
  29. #continue inside the same for loop as above
  30. raw_email_string = raw_email.decode('utf-8')
  31. # converts byte literal to string removing b''
  32. email_message = email.message_from_string(raw_email_string)
  33. # this will loop through all the available multiparts in mail
  34. for part in email_message.walk():
  35. if part.get_content_type() == "text/plain": # ignore attachments/html
  36. body = part.get_payload(decode=True)
  37. #print(email_message.get_all("To")) <----this is where the other email info is
  38. save_string = str(r"C:UsersMillarDesktopSavedEmailsTestDumpgmailemail_" + str(x) + ".eml")
  39. # location on disk
  40. myfile = open(save_string, 'a')
  41. myfile.write(body.decode('utf-8'))
  42. # body is again a byte literal
  43. myfile.close()
  44. else:
  45. continue
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement