1

我需要帮助。这是我要检索的电子邮件。它只是一个纯文本。

在此处输入图像描述

但是当我检索它时,也会检索 html 内容。这是一个例子:在此处输入图像描述

我需要做什么才能只检索黄色框中的消息?

我的代码:

import poplib,os
from email import parser
pop_conn = poplib.POP3_SSL('pop.gmail.com')
pop_conn.user('myemail@gmail.com')
pop_conn.pass_('mypassword')
#Get messages from server:
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
# Concat message pieces:
messages = ['\n'.join(map(bytes.decode, mssg[1])) for mssg in messages]
#Parse message intom an email object:
messages = [parser.Parser().parsestr(mssg) for mssg in messages]

for message in messages:
    sub= message['subject']
    fr=(message['from'])
    for part in message.walk():
        if part.get_content_type():
            body = str(part.get_payload())
            #print(body)
            with open('file_name.txt','r+') as file:
                file.write(sub+'\n')
                file.write(fr+'\n')
                file.write(body+ os.linesep)
                lines=file.readlines()
                lines = [line.rstrip('\n') for line in open('file_name.txt')]
                file.close()
pop_conn.quit()

我尝试使用part.get_payload(decode=True),但 html 内容仍然显示文本消息也打印为一条长直线。

4

0 回答 0