gmail/poplib: quickly detecting new mail

L

LJ

Hello,

I'm trying to monitor my gmail account to know when I have obtained a
new email. It seems that once I have logged in, I should be able to
call the stat() function repeatedly to see how many messages are in my
inbox. The problem is that this number does not seem to update until I
have logged out, and logged back in. In other words, I run the code
below, send myself an email, and observe that the count does not
change. If I kill the program and restart (hence logging back in),
then the total count is now updated. The other function calls seem to
work the same way (eg "list" just shows the same list, even when I know
new mail has arrived).

Questions:
1. is this a standard behavior of pop protocol? (to give me the same
results for any API call on a single login?)
2. OR is this a peculiarity of gmail
3. is there a more efficient and correct way to see know when I have
received a new mail? Currently my "working" method is to log out and
log back in. With this method, I can get about 17 refreshes per minute
but anything faster and Gmail blocks me for a few minutes. (yes it is
important to my application that I have very frequent refreshes).

(see code sample below)

Thanks,
LJ

---

import poplib
import time
from email.Parser import Parser

parser = Parser()
server = poplib.POP3_SSL("pop.gmail.com", 995)
print server.user("XXX-MY_EMAIL")
print server.pass_("XXX-MY_PW")
server.set_debuglevel(0)

def getMsgCount():
# check message count by stat() and list() functions
numMsgs = server.stat()[0]
print "Num msg by stat():", numMsgs
print "Num msg by list():", len(server.list()[1])
print "Most recent:", numMsgs, getSubj(numMsgs)
return

def getSubj(which):
# return subject of message with id 'which'
msg = "\n".join(server.top(which, 1)[1])
email = parser.parsestr(msg)
return email.get("Subject")

while True:
print "--"
getMsgCount()
time.sleep(2)
 
A

Alex Martelli

LJ said:
1. is this a standard behavior of pop protocol? (to give me the same
results for any API call on a single login?)
2. OR is this a peculiarity of gmail

Definitely POP3 standard behavior, as a simple reading of the relevant
RFC will show (e.g., http://www.ietf.org/rfc/rfc1939.txt):
summarizing... on entering Transaction state, a POP3 server acquires an
exclusive lock on the mailbox, to ensure that no modifications occur to
it throughout the session.

I'm not sure about the refresh frequency, but you may want to try the
Atom feed, https://mail.google.com/gmail/feed/atom .


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top