2

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()
user2957378
  • 627
  • 2
  • 14
  • 29
  • the POP3 protocol doesn't support the concept of read or unread messages. You'd have to use IMAP for this. – Gryphius Dec 06 '13 at 21:10
  • @Gryphius Are you sure about that ? Because from the poplib documentation on python (https://docs.python.org/2.6/library/poplib.html#poplib.POP3.retr) it is said that using the "retr" function on a specific email sets this specific email "seen flag". – Michael De Keyser May 19 '14 at 14:49
  • I think the docs are a bit misleading here. the poplib.retr source only sends *RETR * to the server, nothing else. This will cause the server to mark the message as seen - but this is only visible in an IMAP session, I'm pretty sure you can't read the seen flag over POP3. – Gryphius May 19 '14 at 19:33

1 Answers1

0

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.

Paco Barter
  • 182
  • 1
  • 3