Getting UnRead Messages using poplib, Python

4.5k views Asked by At

I'm trying to write some script to check a mail service which uses pop3. As you can see I use poplib module. However, I don't see the correct way to get the unread messages. I found a method which retrieves all the mails so it takes so much time in this call:

messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]

Is there a way to filter the unread messages? Do you know any other good module to deal with pop mail service? Here is the code I'm using:

import poplib
from email import parser
pop_conn = poplib.POP3_SSL('pop3.live.com', 995) #Connect to hotmail pop3 server
pop_conn.user('address')
pop_conn.pass_('password')
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
# Concat message pieces:
messages = ["\n".join(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:
    print "{} : {}\n".format(message['subject'], message['From'])
pop_conn.quit()
1

There are 1 answers

0
Paco Barter On

There's a workaround.

You can use message_count, mailbox_size = pop_conn.stat() to retrieve message_count and store somehow. Later, You can call again pop_conn.stat() and compare message_count with the stored one (remember to update the stored value if it changes). The difference is the "unread" mails.