Python 3 - 如何仅提取电子邮件正文

时间:2017-08-03 14:48:18

标签: python-3.x email decode poplib

我有这段代码来提取邮件正文,但输出显示了邮件和一些加密信息。我需要帮助才能得到消息。

最后一个版本我尝试了lib imaplib,但我没有成功,因为所有消息都是加密的,所以我改为poplib。

作为未来的更新,我想添加主题,日期和发件人

#!/usr/bin/env python3
# -- coding: utf-8 --

import email
import poplib

login = input('Email: ')
password = input('Password: ')
pop_server = 'pop-mail.outlook.com'
pop_port = 995

mail_box = poplib.POP3_SSL(pop_server, pop_port)
mail_box.user(login)
mailbox.pass_(password)
numMessages = len(mail_box.list()[1])

if numMessages > 15:
    numMessages = 15
for i in range(15):
    (server_msg, body, octets) = mail_box.retr(i+1)
    for j in body:
        try:
            msg = email.message_from_string(j.decode("utf-8"))
            strtext = msg.get_payload()
            print(strtext)
        except:
            pass

1 个答案:

答案 0 :(得分:0)

如果a是原始电子邮件字符串:

msg = email.message_from_string(a)
if msg.is_multipart():
    for part in msg.walk():
        payload = part.get_payload(decode=True) #returns a bytes object
        strtext = payload.decode() #utf-8 is default
        print(strtext)
else:
    payload = msg.get_payload(decode=True)
    strtext = payload.decode()
    print(strtext)