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 <jsmith@gmail.com>\r\nSubject: test\r\n\r\n'), ')']
-
conn.fetch(message, '(BODY[HEADER.FIELDS 开发者_如何学JAVA(SUBJECT FROM)])')
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.
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.
精彩评论