I want get only the subject from a message mail using 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()
Any suggestions? Thanks in advance
You need to use email.message_from_bytes
to convert e-mail from bytes and decode_header
to decode your headers. This is python 3.4 example. In python 2 code will be different.
#!/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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.