Advertisement
Guest User

Untitled

a guest
Jan 6th, 2019
322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.33 KB | None | 0 0
  1. import email, getpass, imaplib, os
  2. from os import listdir
  3. from os.path import isfile, join
  4.  
  5. detach_dir = '.' # directory where to save attachments (default: current)
  6. user = input("Enter your GMail username:")
  7. pwd = getpass.getpass("Enter your password: ")
  8.  
  9. # connecting to the gmail imap server
  10. m = imaplib.IMAP4_SSL("imap.gmail.com")
  11. m.login(user, pwd)
  12. m.select('"ICC Games"') # here you a can choose a mail box like INBOX instead
  13. # use m.list() to get all the mailboxes
  14.  
  15. resp, items = m.search("NOT", "SEEN") # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp)
  16. items = items[0].split() # getting the mails id
  17. filenames = []
  18. for emailid in items:
  19.     resp, data = m.fetch(emailid, "(RFC822)") # fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc
  20.     email_body = data[0][1] # getting the mail content
  21.     mail = email.message_from_bytes(email_body) # parsing the mail content to get a mail object
  22.  
  23.      #Check if any attachments at all
  24.      #if mail.get_content_maintype() != 'multipart':
  25.      #   continue
  26.  
  27.     #print(mail["Subject"].split()[2] + "_" + mail["Subject"].split()[4] + "-" + mail["Date"])
  28.  
  29.     # we use walk to create a generator so we can iterate on the parts and forget about the recursive headach
  30.     for part in mail.walk():
  31.         #multipart are just containers, so we skip them
  32.         if part.get_content_maintype() == 'multipart':
  33.             continue
  34.  
  35.         # is this part an attachment ?
  36.         #if part.get('Content-Disposition') is None:
  37.          #   continue
  38.  
  39.         #filename = part.get_filename()
  40.  
  41.         filename = mail["Subject"].split()[2] + "_" + mail["Subject"].split()[4] + "-" + mail["Date"] + ".pgn"
  42.         att_path = os.path.join(detach_dir, filename)
  43.  
  44.         #Check if its already there
  45.         if not os.path.isfile(att_path) :
  46.             # finally write the stuff
  47.             fp = open(att_path, 'wb')
  48.             fp.write(part.get_payload(decode=True))
  49.             fp.close()
  50.             filenames.append(filename)
  51.  
  52.  
  53. with open(os.path.join(detach_dir, "all.pgn"), 'a') as outfile:
  54.     for fname in filenames:
  55.         with open(os.path.join(detach_dir, fname), 'r', encoding='latin1') as infile:
  56.             for line in infile:
  57.                 outfile.write(line)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement