尽管我在从很多网站进行大量搜索后完成了大部分工作,但我仍然无法获得我想要的正确输出。
Code:
import imaplib
import smtplib
import email
mail=imaplib.IMAP4_SSL("imap.gmail.com")
mail.login("**************@gmail.com","********")
mail.select('inbox')
type,data=mail.search(None,'ALL')
mail_ids=data[0]
id_list=mail_ids.split()
for i in range(int(id_list[-1]),int(id_list[0])-1,-1):
typ,data=mail.fetch(i,'(RFC822)')
for response_part in data :
if isinstance(response_part,tuple):
msg=email.message_from_string(response_part[1])
email_from=msg['from']
email_subj=msg['subject']
c=msg.get_payload(0)
print email_from
print "subj:",email_subj
print c
Output:
Bharath Joshi <[email protected] /cdn-cgi/l/email-protection> subj: hehe From nobody Tue
Dec 25 15:48:52 2018 Content-Type: text/plain; charset="UTF-8"
hello444444444
Bharath Joshi <[email protected] /cdn-cgi/l/email-protection> subj: From nobody Tue Dec 25
15:48:52 2018 Content-Type: text/plain; charset="UTF-8"
33333
Bharath Joshi <[email protected] /cdn-cgi/l/email-protection> subj: From nobody Tue Dec 25
15:48:53 2018 Content-Type: text/plain; charset="UTF-8"
hello--22
困扰我的是我得到的额外的东西,即
“没有人......”和“内容类型......”
我怎样才能将它们删除?
啊,电子邮件的“美丽”......显然您面临着多部分电子邮件,对于这些,get_payload()
方法还输出标题。你需要使用msg.walk()
像这样:
for response_part in data :
if isinstance(response_part,tuple):
msg=email.message_from_string(response_part[1])
print "subj:", msg['subject']
print "from:", msg['from']
print "body:"
for part in msg.walk():
if part.get_content_type() == 'text/plain':
print part.get_payload()
要获得更完整的答案,请查看这个 stackoverflow 答案 https://stackoverflow.com/questions/1463074/how-can-i-get-an-email-messages-text-content-using-python
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)