首页 > 解决方案 > 使用 Python 获取 IMAP 的电子邮件接收日期

问题描述

我正在使用以下代码(从 StackOverflow 获取它:))从特定电子邮件地址获取所有未读电子邮件。它完美无缺!

但是,我想获取我从中获取附件的每封电子邮件的实际接收(或发送)日期。但我不知道该怎么做?

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.')

标签: pythonemailimaplib

解决方案


您可以获取该项目的INTERNALDATE替代或补充RFC822;这是(通常)服务器接收消息的时间。

您必须对返回项进行一些解析,因为 imaplib 不解析FETCH结果。如果它是您获取的唯一内容,则解析会更容易。

响应看起来像

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

推荐阅读