Guest User

Untitled

a guest
Dec 26th, 2018
407
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. import email, getpass, imaplib, os
  2.  
  3. detach_dir = '.' # directory where to save attachments (default: current)
  4. user = input("Enter your GMail username:")
  5. pwd = getpass.getpass("Enter your password: ")
  6.  
  7. # connecting to the gmail imap server
  8. m = imaplib.IMAP4_SSL("imap.gmail.com")
  9. m.login(user, pwd)
  10. m.select("cs2043") # here you a can choose a mail box like INBOX instead
  11. # use m.list() to get all the mailboxes
  12.  
  13. resp, items = m.search(None,
  14. "ALL") # you could filter using the IMAP rules here
  15. (check http://www.example-code.com/csharp/imap-search-critera.asp)
  16. items = items[0].split() # getting the mails id
  17.  
  18. for emailid in items:
  19. resp, data = m.fetch(emailid,
  20. "(RFC822)") # fetching the mail, "`(RFC822)`" means
  21. "get the whole stuff", but you can ask for headers only, etc
  22. email_body = data[0][1] # getting the mail content
  23. mail = email.message_from_string(email_body) # parsing the mail content
  24. to get a mail object
  25.  
  26. # Check if any attachments at all
  27. if mail.get_content_maintype() != 'multipart':
  28. continue
  29.  
  30. print
  31. "[" + mail["From"] + "] :" + mail["Subject"]
  32.  
  33. # we use walk to create a generator so we can iterate on the parts and
  34. forget about the recursive headach
  35. for part in mail.walk():
  36. # multipart are just containers, so we skip them
  37. if part.get_content_maintype() == 'multipart':
  38. continue
  39.  
  40. # is this part an attachment ?
  41. if part.get('Content-Disposition') is None:
  42. continue
  43.  
  44. # filename = part.get_filename()
  45.  
  46. filename = mail["From"] + "_hw1answer"
  47.  
  48. att_path = os.path.join(detach_dir, filename)
  49.  
  50. # Check if its already there
  51. if not os.path.isfile(att_path):
  52. # finally write the stuff
  53. fp = open(att_path, 'wb')
  54. fp.write(part.get_payload(decode=True))
  55. fp.close()
  56.  
  57. Traceback (most recent call last):
  58. File "gmail_report_analysis.py", line 9, in <module>
  59. m.login(user, pwd)
  60. File "C:UsersAmirAppDataLocalProgramsPythonPython36libimaplib.py",
  61. line 593, in login
  62. raise self.error(dat[-1])
  63. imaplib.error: b'[AUTHENTICATIONFAILED] Invalid credentials (Failure)'
Add Comment
Please, Sign In to add comment