使用Python IMAP阅读Gmail邮件 [英] Reading Gmail messages using Python IMAP

查看:262
本文介绍了使用Python IMAP阅读Gmail邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管在从许多站点进行了大量搜索之后,我做了大部分工作,但仍然无法获得我想要的正确输出.

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.

代码:

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)主演:呵呵来自无名的星期二 2018年12月25日15:48:52内容类型:文本/纯文本; charset ="UTF-8"

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

hello444444444

hello444444444

巴拉特·乔希(Bharath Joshi)演绎:从没人那里星期二12月25日 15:48:52 2018内容类型:文本/纯文本; charset ="UTF-8"

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

33333

巴拉特·乔希(Bharath Joshi)演绎:从没人那里星期二12月25日 15:48:53 2018内容类型:文本/纯文本; charset ="UTF-8"

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

hello--22

hello--22

困扰我的是我得到的额外的东西.

The thing which is bothering me is the extra thing I'm getting i.e.

来自无人……"和内容类型...".

"From nobody ......" and "Content type ...."

我该如何删除那些人?

推荐答案

啊,电子邮件的美"……显然,您面对的是多部分电子邮件,对于这些,get_payload()方法也将输出标题.您需要像这样使用msg.walk():

Ah, the "beauty" of emails… Apparently you're facing multipart email messages and for these, the get_payload() method is also outputting the headers. You'd need to use msg.walk() like so:

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

这篇关于使用Python IMAP阅读Gmail邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆