· 6 years ago · Jan 09, 2020, 02:00 AM
1# Reads Email, Prints it, and Saves to text file
2import imaplib
3import email
4mail = imaplib.IMAP4_SSL('imap.gmail.com')
5# imaplib module implements connection based on IMAPv4 protocol
6mail.login('superyoshifan101@gmail.com', 'KitKat1000')
7
8# >> ('OK', [username at gmail.com Vineet authenticated (Success)'])
9mail.list() # Lists all labels in GMail
10mail.select('inbox') # Connected to inbox.
11result, data = mail.uid('search', None, "ALL")
12
13# search and return uids instead
14i = len(data[0].split()) # data[0] is a space separate string
15for x in range(i):
16 latest_email_uid = data[0].split()[x] # unique ids wrt label selected
17 result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)')
18 # fetch the email body (RFC822) for the given ID
19 raw_email = email_data[0][1]
20
21#continue inside the same for loop as above
22raw_email_string = raw_email.decode('utf-8')
23# converts byte literal to string removing b''
24email_message = email.message_from_string(raw_email_string)
25# this will loop through all the available multiparts in mail
26for part in email_message.walk():
27 if part.get_content_type() == "text/plain": # ignore attachments/html
28 body = part.get_payload(decode=True)
29 save_string = str("Data" + str(x) + ".txt")
30 # location on disk
31 myfile = open(save_string, 'a')
32 myfile.write(body.decode('utf-8'))
33 # body is again a byte literal
34 myfile.close()
35 else:
36 continue
37print(body.decode('utf-8'))