在Python 2.7中下载IMAP文件附件时出现损坏

时间:2017-04-28 21:00:11

标签: python imap email-attachments

我正在从IMAP电子邮件下载文件附件。代码如下:

header = '(' +  'SUBJECT '+ '"' +'A SPECIFIED MESSAGE HEADER'"' + ')'

# Connect to an IMAP server
def connect(server, user, password):
    m = imaplib.IMAP4_SSL(server)
    m.login(user, password)
    m.select()
    return m

# Download all attached files 

def downloadAttachmentsInEmail(m, emailid, outputdir):
    resp, data = m.fetch(emailid, "(BODY.PEEK[])")
    email_body = data[0][1]
    mail = email.message_from_string(email_body)

    # check for attachment;
    for part in mail.walk():
        if not mail.is_multipart():
            continue
        if mail.get('Content-Disposition'):
            continue
        file_name = part.get_filename()

        if file_name:
            file = open(outputdir + '/' + file_name,'w+')
            file.write(part.get_payload(decode=True))
            file.close()

m = connect(<IMAP SERVER>,<EMAIL ACCOUNT>,<PASSWORD>)

m.select('INBOX', readonly=True)
typ, emailid = m.search(None, header)
downloadAttachmentsInEmail(m, emailid[0], outputdir)

代码工作正常。当我在下载后检查输出目录时,一切看起来都不错。但是,当我尝试打开文件(excel文件和pdfs)时,我无法得到损坏错误。

建议?

提前致谢。

0 个答案:

没有答案