使用 Python IMAP 阅读 Gmail 邮件

Reading Gmail messages using Python IMAP

虽然我在从很多网站上搜索了很多之后做了大部分工作,但我仍然无法获得我想要的正确输出。

代码:

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

输出:

Bharath Joshi subj: hehe From nobody Tue Dec 25 15:48:52 2018 Content-Type: text/plain; charset="UTF-8"

hello444444444

Bharath Joshi subj: From nobody Tue Dec 25 15:48:52 2018 Content-Type: text/plain; charset="UTF-8"

33333

Bharath Joshi subj: From nobody Tue Dec 25 15:48:53 2018 Content-Type: text/plain; charset="UTF-8"

hello--22

困扰我的是我得到的额外东西,即

"From nobody ......" 和 "Content type ...."

我怎样才能删除那些?

啊,"beauty" 的电子邮件……显然你面对的是多部分电子邮件,对于这些,get_payload() 方法也输出 headers。您需要像这样使用 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()

要获得更完整的答案,请查看 this Whosebug answer