StasM StasM - 3 months ago 54
Python Question

Parsing IMAP responses in python

I am using imaplib to work with imap in python, however it looks like it doesn't have means to parse the details of IMAP responses. For example, query like:

msgdata = connection.fetch(num, "(BODY.PEEK[HEADER.FIELDS (FROM TO CC DATE SUBJECT MESSAGE-ID)] UID)")

is the message number, for one mail server may produce (for example):

('OK', [('1234 (BODY[HEADER.FIELDS (FROM TO CC DATE SUBJECT MESSAGE-ID)] {123}', 'From: ...etc headers'), ' UID 3456)'])

and for another:

('OK', [('1234 (UID 3456 BODY[HEADER.FIELDS (FROM TO CC DATE SUBJECT MESSAGE-ID)] {123}', 'From: ...etc headers'), ')'])

As you see, the message details are different and UID is even in different element there. So the question is - is there some library that would allow to automatically sort it out and abstract the details of what particular mail server does?


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.