简体   繁体   中英

Get e-mail recieved date of IMAP using Python

I'm using the following code (got it from StackOverflow :)) to get all unread e-mail from specific email adresses. It works perfect!

I would however like to get the actual recived (or sent) date for each e-mail I'm getting an attached file from. But I dont know how to do that?

import email
import imaplib
import os
import sys
import random
import string
import glob
import unicodedata

def remove_accents(s):
    nkfd_form = unicodedata.normalize('NFKD', s)
    return u''.join([c for c in nkfd_form if not unicodedata.combining(c)])

def remove_non_ascii(text):
    return unidecode(unicode(text, encoding = "cp865"))

def replace_non_ascii(x): return ''.join(i if ord(i) < 128 else '_' for i in x)

detach_dir = r'\\1.1.1.1\xxx\xxx\drop_folder'

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

    imapSession.select('Inbox')
    typ, data = imapSession.search(None, '(UNSEEN FROM "@xxxx.xxx")')
    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().encode('utf-8')

        if bool(fileName):
            filePath = os.path.join(detach_dir, 'EXP-' + fileName + '.xls')
            if not os.path.isfile(filePath) :
                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.')

You could fetch the INTERNALDATE instead of, or in addition to the RFC822 item; It is (generally) time the server received the message.

You will have to do some parsing of the return item, since imaplib does no parsing of FETCH results. It will be easier to parse if it's the only thing you fetch.

The response will look something like

* 5 FETCH (INTERNALDATE "17-Jul-2018 02:44:25 -0700")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM