我写了一个代码来阅读电子邮件并打印其内容。我想创建一个有序的字典,并将.items()中存在的电子邮件属性转换为dict,并且还想在字典中打印正文部分,而不是在msg.items()中。我该如何实现?
import email
import imaplib2
from collections import OrderedDict
....
def read_mail_from_server():
try:
mail = imaplib2.IMAP4_SSL(EMAIL_SERVER, 993)
mail.login(EMAIL_USER, EMAIL_PASSWORD)
mail.select('INBOX')
typ, raw_data = mail.search(None, 'ALL')
mail_ids = raw_data[0]
for i in mail_ids.split():
result, msg_data = mail.fetch(i, '(RFC822)')
for each_response in msg_data:
if isinstance(each_response, tuple):
msg = email.message_from_string(each_response[1])
email_subject = msg['subject']
print('Subject:' + email_subject + '\n')
email_from = msg['from']
print('From:' + email_from + '\n')
items_list = msg.items()
print(items_list)
dict_items = OrderedDict(items_list)
print(dict_items)
body = ''
if msg.is_multipart():
for part in msg.walk():
ctype = part.get_content_type()
disp = str(part.get('Content-Disposition'))
if ctype == 'text/plain' and 'attachment' not in disp:
body = part.get_payload()
break
else:
body = msg.get_payload(decode=True)
print('body:' + body + '\n')
except Exception, e:
print str(e)
read_mail_from_server()
我得到的输出:
[('Return-Path', '<name@mail.com>'), ('Delivered-To',
'recipient@mail.com'), ('Delivery-date', 'Tue, 14 May 2019 14:07:07
+0530'), ('Subject', 'Fw: Tuesday'), ('Importance', 'Normal')]
Body:
URGENT: Sensitive Classifier Alert
我期望的输出:
{
'Body':
{
URGENT: Sensitive Classifier Alert
}
'Delivered-To':'recipient@mail.com'
'Delivery-date':'Tue, 14 May 2019 14:07:07+0530'
'Return-Path':'<name@mail.com>'
....
}