我正在尝试从 IMAP 获取未读邮件。当我尝试解析电子邮件内容时,我得到len(email_message.keys()) == 0
. 所以我永远不会得到From
和。To
Subject
打印的电子邮件 ( 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