import sys, imaplib
from email.parser import HeaderParser
mail = imaplib.IMAP4_SSL(SERVER, PORT)
status, data = mail.search(None, 'ALL')
for msg_id in data[0].split():
status, message = mail.fetch(msg_id, '(RFC822)')
print message[0][1]
mail.close()
mail.logout()
我正在尝试通过imap从gmail中获取电子邮件。一切正常,但我无法从邮件中提取标题(主题,发件人,日期)。在上面的代码中,消息[0] [1]包含我的电子邮件。
我能够获得标题的唯一方法是再次询问imap服务器,特别是标题:
status, message = mail.fetch(msg_id, '(BODY[HEADER.FIELDS (SUBJECT FROM)])')
parser = HeaderParser()
header = parser.parsestr(message[0][1])
print header
有人可以建议怎么做吗?
答案 0 :(得分:8)
我假设您已收到完整的电子邮件,而不仅仅是邮件正文。
raw_message = """From: Santa Claus <santa@aintreal.no>
To: Some Dude <some@du.de>
Subject: I have lost your presents.
Dude, i am so sorry.
"""
import email
msg = email.message_from_string(raw_message)
print(msg['Subject']) # "I have lost your presents."
msg
是email.message.Message
个对象。