0

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()
abn
  • 1,353
  • 4
  • 28
  • 58
  • Once you have the data you want to save, use [csv.writer](https://docs.python.org/3/library/csv.html#csv.writer) to create an object and write the data onto it. It's not harder than writing to a regular file. – user3557327 Aug 04 '14 at 22:33
  • @user3557327 Thank you for your response. I have more than 1000 outputs from a website and I'd like to download those into separate CSV files. I cannot run the program 1000 times. – abn Aug 04 '14 at 22:38
  • Why do you think user3557327's suggestion requires that you run the program 1000 times? – Ross Ridge Aug 04 '14 at 22:48
  • @RossRidge I have no idea how to automate it. I'd really appreciate if you could help me with it. Thank you. – abn Aug 04 '14 at 22:51

1 Answers1

0
if not os.path.isfile(att_path) :
        for files in att_path:
            data = content.replace(" ", ",") #replaces if the delimiter is anything other than a ",". 
            fp = open(att_path+".csv", 'wb')
            fp.write(data)
            fp.close()

This would write the files properly delimited

user3783999
  • 571
  • 2
  • 7
  • 17