1

我正在尝试从 IMAP 获取未读邮件。当我尝试解析电子邮件内容时,我得到len(email_message.keys()) == 0. 所以我永远不会得到From和。ToSubject

打印的电子邮件 ( email.message_from_string(email_str)):

From nobody Fri Sep 14 13:42:50 2012

1 (RFC822 {1015}
Return-Path: <sender@domain.com>
X-Original-To: recepient@domain.com
Delivered-To: recepient@domain.com
Received: from ec2.....amazonaws.com (unknown [IP])
    (Authenticated sender: sender@domain.com)
    by domain.com (Postfix) with ESMTPA id EACD436CF
    for <recepient@domain.com>; Fri, 14 Sep 2012 12:47:54 +0000 (UTC)
DKIM-Signature: ....
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
From: sender@domain.com
To: recepient@domain.com
Subject: welcome

Dear recipient,

Welcome.

Best,
Robot

这是代码:

def fetch_new_emails(host, port, user, password):
  conn = imaplib.IMAP4(host=host, port=port)

  try:
    (retcode, capabilities) = conn.login(user, password)
    conn.select(readonly=1) # Select inbox or default namespace
    (retcode, messages) = conn.search(None, '(UNSEEN)')
    results = []
    if retcode == 'OK':
      for message in messages[0].split(' '):
        (ret, raw_email) = conn.fetch(message, '(RFC822)')
        if ret == 'OK':
          print raw_email[0]
          email_str = string.join(raw_email[0], "\n")
          email_message = email.message_from_string(email_str)
          email_from = email_message['From']
          to = email_message['To']
          subject = email_message['Subject']
          results.append({
            'from': email_from, 
            'to': to,
            'subject': subject})
  except:
    print sys.exc_info()[1]
    sys.exit(1)
  finally:
    conn.close()
  return results

问题:

print email_message['From']
>>None    
print email_message['To']
>>None
print email_message['Subject']
>>None
4

1 回答 1

2

行后有一个奇怪的空From nobody...行。从技术上讲,空行是标题的结尾,之后的所有内容都是正文,因此消息实际上没有这些标题。

无论如何,IMAP 消息不应该有From一行(这是典型的 Berkeley mbox 格式,很少有 IMAP 服务器使用这种格式;即使你的有,它的存储实现的这个细节也不应该对 IMAP 客户端可见)。

奇怪的1 (RFC822 {1015}线也不属于;它看起来有点像是 IMAP 协议响应的一部分,而不是实际消息的一部分。Return-Path:在这种特殊情况下,正确的消息以标头开头。

IMAP 服务器和/或客户端代码不是生产版本吗?

于 2012-09-14T14:22:00.493 回答