1

I am trying to download csv file in my email attachment using this link : Download a csv file from gmail using python

It doesn't show any error and The program says 'Process finished with exit code 0' but it doesn't download any attachments either. I tried to print some variables but it doesn't get print.

Is it a gmail issue or is there anything wrong with the code?

import getpass
import imaplib
import os
import sys

userName = 'abc@gmail.com'
passwd = 'password'
directory = 'c:/users/pictures'


detach_dir = '.'
if 'DataFiles' not in os.listdir(detach_dir):
    os.mkdir('DataFiles')


    imapSession = imaplib.IMAP4_SSL('imap.gmail.com')
    typ, accountDetails = imapSession.login(userName, passwd)
    print(typ)
    if typ != 'OK':
        print ('Not able to sign in!')
        raise()

    imapSession.select('[Gmail]/All Mail')
    typ, data = imapSession.search(None, 'ALL')
    print(typ)
    if typ != 'OK':
        print ('Error searching Inbox.')
        raise ()


    for msgId in data[0].split():
        typ, messageParts = imapSession.fetch(msgId, '(RFC822)')
        print(typ)
        if typ != 'OK':
            print ('Error fetching mail.')
            raise ()

        emailBody = messageParts[0][1]
        emailBody = emailBody.decode('utf-8')
        mail = email.message_from_string(emailBody)
        for part in mail.walk():
            if part.get_content_maintype() == 'multipart':
                continue
            if part.get('Content-Disposition') is None:
                continue
            fileName = part.get_filename()

            if bool(fileName):
                filePath = os.path.join(detach_dir, 'DataFiles', fileName)
                if not os.path.isfile(filePath) :
                    print (fileName)
                    fp = open(filePath, 'wb')
                    fp.write(part.get_payload(decode=True))
                    print('file written')
                    fp.close()
    imapSession.close()
    imapSession.logout()

    print ('Done')

the_badev
  • 47
  • 6

0 Answers0