[英]Reading Gmail messages using Python IMAP
Though I did most of it after searching a lot from lots of sites I am still not able to get the correct output which I wanted. 尽管在从许多站点进行了大量搜索之后,我做了大部分工作,但仍然无法获得所需的正确输出。
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 subj: hehe From nobody Tue Dec 25 15:48:52 2018 Content-Type: text/plain; 巴拉特·乔希(Bharath Joshi)主题:hehe来自没人星期二2018年12月25日星期二15:48:52内容类型:text / plain; charset="UTF-8" charset =“ UTF-8”
hello444444444 你好444444444
Bharath Joshi subj: From nobody Tue Dec 25 15:48:52 2018 Content-Type: text/plain; 巴拉特·乔希(Bharath Joshi)主题:从没人那里星期二十二月25 15:48:52内容类型:text / plain; charset="UTF-8" charset =“ UTF-8”
33333 33333
Bharath Joshi subj: From nobody Tue Dec 25 15:48:53 2018 Content-Type: text/plain; 巴拉特·乔希(Bharath Joshi)主题:从没人那里,星期二,十二月25 15:48:53 2018内容类型:text / plain; charset="UTF-8" charset =“ UTF-8”
hello--22 你好-22
The thing which is bothering me is the extra thing I'm getting ie 困扰我的是我得到的额外的东西,即
"From nobody ......" and "Content type ...." “来自……”和“内容类型……”。
How can I get those removed? 我如何去除那些?
Ah, the "beauty" of emails… Apparently you're facing multipart email messages and for these, the get_payload()
method is also outputting the headers. 啊,电子邮件的“美丽”……显然,您面对的是多部分电子邮件,对于这些, get_payload()
方法也将输出标头。 You'd need to use msg.walk()
like so: 您需要像这样使用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()
For a more complete answer have a look at this stackoverflow answer 要获得更完整的答案,请查看此stackoverflow答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.