使用poplib python获取消息头(主题)

时间:2013-05-22 10:28:01

标签: python poplib

我想使用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()

有什么建议吗?提前致谢

1 个答案:

答案 0 :(得分:1)

您需要使用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()