Andrew
Andrew

Reputation: 3999

Get email subject and sender using imaplib?

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)])')

Upvotes: 2

Views: 21755

Answers (2)

Avadhesh
Avadhesh

Reputation: 4703

You can try this to fetch the header information of all the mails.

import imaplib
import email

obj = imaplib.IMAP4_SSL('imap.gmail.com', 993)
obj.login('username', 'password')
obj.select('folder_name')
resp, data = obj.uid('FETCH', ','.join(map(str,uidl_list)) , '(BODY.PEEK[HEADER.FIELDS (From Subject)] RFC822.SIZE)')

Note: Here 'uidl_list' is the list of uid of mails whose subject u want.

Upvotes: 4

Femi
Femi

Reputation: 64700

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.

Upvotes: 8

Related Questions