Parsing IMAP responses in python
Doug Hellman's Python Module of the Week entry for imaplib is a fairly extensive tutorial on the subject, but is far to long to reproduce here.
You might want to use a higher level library like IMAPClient to hide some of the details of the IMAP protocol.