简体   繁体   English

使用Python获取IMAP的电子邮件接收日期

[英]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. 我正在使用以下代码(从StackOverflow中获取了它:))来获取来自特定电子邮件地址的所有未读电子邮件。 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; 您可以获取INTERNALDATE来代替RFC822项,或者在RFC822项之外获取。 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. 您将必须对返回项进行一些解析,因为imaplib不会解析FETCH结果。 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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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