Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import imaplib
- import email
- #Login
- mail = imaplib.IMAP4_SSL('imap.gmail.com')
- # imaplib module implements connection based on IMAPv4 protocol
- mail.login('email', 'pswd')
- # >> ('OK', [username at gmail.com Vineet authenticated (Success)'])
- #Selecting a label
- mail.list() # Lists all labels in GMail
- mail.select('inbox') # Connected to inbox
- #Searching Through Inbox
- result, data = mail.search(None, "ALL")
- # search and return uids instead
- ids = data[0] #data is a list
- id_list = ids.split() #ids is a space separated string
- i = len(data[0].split())
- for x in range(i):
- latest_email_id = id_list[x] #get the latest
- result, data = result, data = mail.fetch(latest_email_id, "(RFC822)") # fetch the email body (RFC822) for the given ID
- raw_email = data[0][1] # here's the body, which is raw text of the whole email
- #Parsing raw email
- print("loop")
- #continue inside the same for loop as above
- raw_email_string = raw_email.decode('utf-8')
- # converts byte literal to string removing b''
- email_message = email.message_from_string(raw_email_string)
- # this will loop through all the available multiparts in mail
- for part in email_message.walk():
- if part.get_content_type() == "text/plain": # ignore attachments/html
- body = part.get_payload(decode=True)
- #print(email_message.get_all("To")) <----this is where the other email info is
- save_string = str(r"C:UsersMillarDesktopSavedEmailsTestDumpgmailemail_" + str(x) + ".eml")
- # location on disk
- myfile = open(save_string, 'a')
- myfile.write(body.decode('utf-8'))
- # body is again a byte literal
- myfile.close()
- else:
- continue
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement