使用imap python读取看不见的电子邮件的正文(仅文本)

2024-10-01 02:28:08 发布

您现在位置: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()

我得到的结果是

^{pr2}$

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


Tags: comidreadsearchresponsestatusmsggmail
1条回答
网友
1楼 · 发布于 2024-10-01 02:28:08

你得到的是原始邮件。有一个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/

相关问题 更多 >