tags:

views:

326

answers:

2

I am trying to write a program that monitors an IMAP mailbox and automatically copies every new incoming message into an "Archive" folder. I'm using imaplib2 which implements the IDLE command. Here's my basic program:

M = imaplib2.IMAP4("mail.me.com")
M.login(username,password)
lst = M.list()
assert lst[0]=='OK'
for mbx in lst[1]:
    print "Mailboxes:",mbx

def process(m):
    print "m=",m
    res = M.recent()
    print res


M.select('INBOX')
M.examine(mailbox='INBOX',callback=process)
while True:
    print "Calling idle..."
    M.idle()
    print "back from idle"
M.close()
M.logout()

It prints the mailboxes properly and runs process() when the first change happens to the mailbox. But the response from recent() doesn't make sense to me, and after the first message I never get any other notifications.

Anyone know how to do this?

+1  A: 

See example and references in python-imap-idle-with-imaplib2. The module involves threading, you should pay attention to event synchronization.

The example suggests synchronizing with events, and leaves mail processing to the reader:

# The method that gets called when a new email arrives. 
# Replace it with something better.
def dosync(self):
    print "Got an event!"

Taking a hint from the question, "something better" can be:

# Replaced with something better.
def dosync(self):
    print "Got an event!"
    res = self.M.recent()
    print res
gimel
Thanks. But the code only alerts each time a message is returned; how do I get the UID of the messsage so that I can do something with it?
vy32
Added something you can try.
gimel
Thanks. I'm putting together a app now!
vy32
A: 

I am finding that recent() is a bit vague (this is an IMAP vagueness, not imaplib2). Seems better to keep a list of message numbers before and after idle, and the difference is new messages.

Then use fetch(messages,"UID") to get the message uid.

Paul
Yeah. recent() ended up not working for me. I've also had problems with imaplib2() - it just freezes up after running for a few hours. Not sure how to proceed...Do you have code that works?
vy32