Imaplib下载附件?

时间:2017-02-28 20:13:07

标签: python windows python-2.7

我尝试合并一个脚本,在电子邮件中下载附件并将其保存到目录中。我去过无数的论坛 - 我似乎找到了正确的代码,唯一的问题是脚本将所有附件保存在电子邮件中(包括可能在签名中的任何图片等) 。代码如下:

import email
import getpass, imaplib
import os
import sys

detach_dir = 'C:\\Users\\John\\Downloads'

userName = "<<an email>>"
passwd = "<<a password>>"

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

imapSession.select('INBOX')
typ, data = imapSession.search(None, 'UNSEEN')
if typ != 'OK':
    print 'Error searching Inbox.'
    raise

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

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

        if bool(fileName):
            filePath = os.path.join(detach_dir, 'attachments', fileName)
            if not os.path.isfile(filePath) :
                print fileName
                fp = open(filePath, 'wb')
                fp.write(part.get_payload(decode=True))
                fp.close()
imapSession.close()
imapSession.logout()
except :
print 'Not able to download all attachments.'

理想情况下,我希望只阅读&#34;未读&#34;消息,下载附加的文件,并将它们保存到目录中。我通过Office365使用Outlook帐户,如果这有所作为。

0 个答案:

没有答案