使用python从电子邮件下载zip文件

时间:2018-11-30 01:57:19

标签: python email zipfile

我正在使用以下代码(从https://gist.github.com/jasonrdsouza/1674794进行修改)从我的gmail下载zip文件。我可以下载文件,但是该文件不是正确的zip文件,因此无法解压缩。有人知道吗?谢谢!!!

import email, getpass, imaplib, os

user = 'MYNAME'
pwd = 'MYPWD'

m = imaplib.IMAP4_SSL('imap.gmail.com')

m.login(user,pwd)

m.select("inbox")

resp, items = m.search(None, "FROM JOHN@YAHOO.com")

items = items[0].split()

for emailid in items:
    resp, data = m.fetch(emailid, "(RFC822)")
    email_body = data[0][1]
    mail = email.message_from_bytes(email_body)

    if mail.get_content_maintype() != 'multipart':
        continue

#     print("[" + mail['From'] + "] :" + mail["Subject"])

    for part in mail.walk():
        if part.get_content_maintype() == 'multipart':
            continue

        if part.get('Content-Disposition') is None:
            continue

        if "KEYWORD" in mail["Subject"]:           
            dir_save = 'DIRECTORY'
            fileName = 'FILENAME'
            att_path = os.path.join(dir_save, fileName)

            if not os.path.isfile(att_path):
                fp = open(att_path, 'wb')
                fp.write(part.get_payload(decode=True))
                fp.close()
            else:
                break

0 个答案:

没有答案