Gmail附件未从python程序下载

时间:2020-03-02 21:05:40

标签: python gmail gmail-imap

我正在尝试使用以下链接下载电子邮件附件中的csv文件:documentation

它没有显示任何错误,并且程序显示“进程已完成,退出代码为0”,但也没有下载任何附件。我试图打印一些变量,但没有得到打印。

是Gmail问题,还是代码有问题?

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')

0 个答案:

没有答案