I'm trying to download data from unread emails into csv files, in the sense, each unread email data goes into a separate csv file. I'm able to use imaplab and email to get the body of unread emails but I do not know how to save them into separate csv files and name them with the first line of the email body. Here's my code so far.
import imaplib
import email
server = imaplib.IMAP4_SSL('imap.gmail.com')
server.login('email@gmail.com', 'password')
server.select('[Gmail]/All Mail')
resp, items = server.search(None, "(UNSEEN)")
for mail in items[0].split():
resp, data = server.fetch(mail, '(RFC822)')
body = data[0][1]
msg = email.message_from_string(body)
content = msg.get_payload(decode=True)
print content
Thank you.
SOLUTION:
import email, imaplib, os
detach_dir = '.'
# connecting to the gmail imap server
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login('email@gmail.com', 'password')
m.select("[Gmail]/All Mail")
resp, items = m.search(None, "(UNSEEN)")
for mail in items[0].split():
resp, data = m.fetch(mail, '(RFC822)')
body = data[0][1]
msg = email.message_from_string(body)
content = msg.get_payload(decode=True)
filename = content[2:7]
counter = 1
if not filename:
filename = 'part-%03d%s' % (counter, 'bin')
counter += 1
file_path = os.path.join(detach_dir, filename)
if not os.path.isfile(file_path) :
fp = open(file_path+".csv", 'wb')
fp.write(content)
fp.close()
m.logout()