reading only new messages in imaplib

Tony Meyer t-meyer at ihug.co.nz
Wed Feb 23 18:45:32 EST 2005


[Raghul]
>>> Is it posssible to read only the new messages or unread
>>> messages using imaplib in python? If it is possible pls 
>>> specify the module or give a sample code.

[Tony Meyer]
>> This will print out the first 20 chars of each undeleted message. 
>> You should be able to figure out how to do what you want from it.
[...]

[Raghul]
> Received: by twmail.
> Received: from mail.
[...]
> it prints something like this. what it actually display.

Did you read what I wrote, or just run the code?  As I said, it displays the
first 20 characters of each undeleted message.  If you can't see where the
'first 20 characters' bit is in the code, then you really need to forget
about IMAP for the moment and start with the Python tutorial.

> And pls tell me what it actually does? I can't understand

>>> import imaplib

Imports the imaplib module.

>>> i = imaplib.IMAP4("mail.example.com")

Creates an imaplib.IMAP4 instance to be connected to the mail.example.com
server.

>>> i.login("username", "password")

Logs into the server with the username "username" and the password
"password".

>>> i.select()

Selects the inbox.

>>> for msg_num in i.search(None, "UNDELETED")[1][0].split():

Does an IMAP search for UNDELETED messages.  Assumes that [0] of the
response is "OK" and that [1] of the response is a tuple of the string of
the ids.  Splits the string on whitespace and iterates through it.

... 	msg = i.fetch(str(msg_num), "RFC822")

Fetches the message (header and body in RFC822 format) for the given message
number.

... 	print msg[1][0][1][:20]

Digs down through the response (use imaplib.debug = 4 to see it) to get the
message as a string.  Prints out 20 characters of it.

As basically everyone has said, you must read the IMAP RFC and understand it
in order to use imaplib.  Please do so.

=Tony.Meyer




More information about the Python-list mailing list