Get email subject and sender using imaplib?

Andrew picture Andrew · Jun 2, 2011 · Viewed 20.4k times · Source

I am getting the following response after executing the code shown below the response. How can I parse through this response to get the sender (John Smith) and the subject (test)?

[('13010 (BODY[HEADER.FIELDS (SUBJECT FROM)] {57}', 'From: John Smith <[email protected]>\r\nSubject: test\r\n\r\n'), ')']

-

conn.fetch(message, '(BODY[HEADER.FIELDS (SUBJECT FROM)])')

Answer

Femi picture Femi · Jun 2, 2011

Perhaps the question/answer here will help. Try something like this:

from email.parser import HeaderParser
data = conn.fetch(message, '(BODY[HEADER.FIELDS (SUBJECT FROM)])')
header_data = data[1][0][1]
parser = HeaderParser()
msg = parser.parsestr(header_data)

and then msg should be a dictionary.