简体   繁体   中英

Getting UnRead Messages using poplib, Python

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()

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM