Get email subject and sender using imaplib?

拜拜、爱过 提交于 2019-12-10 11:25:56

问题


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 (SUBJECT FROM)])')

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6209616/get-email-subject-and-sender-using-imaplib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!