· 9 years ago · Oct 27, 2016, 02:54 PM
1import imaplib
2import email
3
4#Login
5mail = imaplib.IMAP4_SSL('imap.gmail.com')
6# imaplib module implements connection based on IMAPv4 protocol
7mail.login('email', 'pswd')
8# >> ('OK', [username at gmail.com Vineet authenticated (Success)'])
9
10#Selecting a label
11
12mail.list() # Lists all labels in GMail
13mail.select('inbox') # Connected to inbox
14
15#Searching Through Inbox
16
17result, data = mail.search(None, "ALL")
18# search and return uids instead
19ids = data[0] #data is a list
20id_list = ids.split() #ids is a space separated string
21i = len(data[0].split())
22for 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