imaplib question - answering my own question
Laszlo Nagy
gandalf at designaproduct.biz
Fri Jul 14 12:08:53 EDT 2006
Laszlo Nagy írta:
> Laszlo Nagy írta:
>
>> Hello,
>>
>> I'm trying to write a very simple program that moves all messages from
>> INBOX into another folder.
>> I'm not sure what am I doing wrong. This is a very simple task. I
>> believe I need to call these methods:
>>
>> - search -> get all message UIDs in the INBOX
>> - copy -> copy all messages to another folder
>> - store -> mark all messages in INBOX as deleted
>> - expunge -> delete them physically
>>
>>
Here is the solution - code to move all messages from SOURCE_FOLDER to
DEST_FOLDER
self.logger.info('Connecting to IMAP server...')
conn = getnewimapconnection()
cnt = 0
try:
typ,data = conn.select(local.SOURCE_FOLDER)
check_error((typ,data))
cnt = int(data[0])
if cnt > 0:
self.logger.info("Moving %s messages from %s to
%s",cnt,local.SOURCE_FOLDER,local.DEST_FOLDER)
# Get uids for all messages
typ,all_messages = conn.uid('SEARCH',None,'ALL')
check_error((typ,data))
uids = all_messages[0].split()
# Store all messages into another folder
for uid in uids:
check_error(conn.uid('COPY',uid,local.DEST_FOLDER))
# Delete all messages from inbox
for uid in uids:
check_error(conn.uid('STORE',uid,'+FLAGS.SILENT','(\\Deleted)'))
conn.expunge()
else:
self.logger.info("No new messages in
%s",local.SOURCE_FOLDER)
finally:
conn.logout()
Here is the connection factory:
class IMAPError(Exception):
pass
def check_error((typ,data)):
if (typ != 'OK'):
raise IMAPError((typ,data))
def getnewimapconnection():
conn = imaplib.IMAP4_SSL(local.IMAP_HOST)
check_error(conn.LOGIN(local.IMAP_LOGIN,local.IMAP_PWD))
return conn
I should still check if the operations can be done in bulk (e.g. for
many uids at the same time). Is this possible? I don't know.
Best,
Laszlo
More information about the Python-list
mailing list