使用imap python阅读未见过的电子邮件的正文(仅文本)

时间:2015-03-24 10:41:30

标签: python

下面是我用来阅读帐户中看不见的邮件的代码

import imaplib


def read():
    # Login to INBOX
    imap = imaplib.IMAP4_SSL("imap.gmail.com", 993)
    imap.login("noticeboard16@gmail.com","embeddedSystems")
    imap.select('INBOX')

    # Use search(), not status()
    status, response = imap.search('INBOX', '(UNSEEN)')
    unread_msg_nums = response[0].split()

    # Print the count of all unread messages
    print len(unread_msg_nums)

    # Print all unread messages from a certain sender of interest
    status, response = imap.search(None,"UNSEEN")
    unread_msg_nums = response[0].split()
    da = []
    for e_id in unread_msg_nums:
        _, response = imap.fetch(e_id, '(UID BODY[TEXT])')
        da.append(response[0][1])
    print da

    # Mark them as seen
    for e_id in unread_msg_nums:
        imap.store(e_id, '+FLAGS', '\Seen')



read()

我得到的结果是

['------=_Part_394017_525061083.1427193122764\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\nshsidghsdiuhhgsghshgiurhguirghursgdsjlvn =C2=A0dfh\r\n=20\r\n\r\n\r\n     On Tuesday, March 24, 2015 3:40 PM, Nethmi Hettiarachchi <hettiarachch=\r\ni.nethmi@yahoo.com> wrote:\r\n  =20\r\n\r\n ygfadyfgsduygfvadyugvsuydzgvfhfgd=20\r\n\r\n\r\n     On Tuesday, March 24, 2015 2:49 PM, Nethmi Hettiarachchi <hettiarachch=\r\ni.nethmi@yahoo.com> wrote:\r\n  =20\r\n\r\n hello notice board..CO321 lab is candelled..=20\r\n\r\n\r\n     On Tuesday, March 24, 2015 9:23 AM, Nethmi Hettiarachchi <hettiarachch=\r\ni.nethmi@yahoo.com> wrote:\r\n  =20\r\n\r\n hello..this is co321.group project=20\r\n\r\n\r\n     On Tuesday, Mar

上面的内容包括我收到的消息,但我只需要打印消息

1 个答案:

答案 0 :(得分:1)

你得到的是原始电子邮件。有一个python库电子邮件,可以帮助您解析原始电子邮件:

import email

email_message = email.message_from_string(raw_email)


print email_message['To']

print email.utils.parseaddr(email_message['From']) # for parsing "Yuji Tomita" <yuji@grovemade.com>

print email_message.items() # print all headers

# note that if you want to get text content (body) and the email contains
# multiple payloads (plaintext/ html), you must parse each message separately.
# use something like the following: (taken from a stackoverflow post)
def get_first_text_block(self, email_message_instance):
    maintype = email_message_instance.get_content_maintype()
    if maintype == 'multipart':
        for part in email_message_instance.get_payload():
            if part.get_content_maintype() == 'text':
                return part.get_payload()
    elif maintype == 'text':
        return email_message_instance.get_payload()

以下是有关获取原始电子邮件(您做了什么)和解析原始电子邮件(您想要的内容)的更多信息

https://yuji.wordpress.com/2011/06/22/python-imaplib-imap-example-with-gmail/