3

我只想使用 poplib 从邮件中获取主题:

import poplib
server ='pop3.live.com'
port = 995
login="xxx@outlook.com"
pw="xxx"
print "Connecting..."
M = poplib.POP3_SSL(server,port)
print "Connected to "+server
M.user(login)
M.pass_(pw)
print login+" is authenticated."
numMessages = len(M.list()[1])
for i in range(numMessages):
    for j in M.retr(i+1)[1]:
        print j
M.quit()

有什么建议么?提前致谢

4

1 回答 1

6

您需要使用email.message_from_bytes将电子邮件从字节转换并decode_header解码您的标题。这是python 3.4示例。在python 2中,代码会有所不同。

#!/usr/bin/env python3

import email, poplib
from email.header import decode_header

login = 'login'
password = 'password'
pop_server = 'gmail.com'
pop_port = 995

mail_box = poplib.POP3_SSL(pop_server, pop_port)
mail_box.user(login)
mail_box.pass_(password)

num_messages = len(mail_box.list()[1])
for i in range(num_messages):
    print(i, "message:")

    raw_email  = b"\n".join(mail_box.retr(i+1)[1])
    parsed_email = email.message_from_bytes(raw_email)

    subject = decode_header(parsed_email['Subject'])
    print(
        subject[0][0].decode(subject[0][1])
    )

mail_box.quit()
于 2016-10-06T14:55:06.303 回答