Search code examples
pythonimap

Working with IMAP using UIDs


I have created 5 messages in a brand new test IMAP folder. Then message 3 got deleted, so UIDs of the remaining messages are [1, 2, 4, 5].

Now I'm trying to list all messages starting from a certain UID. Here is a Python code:

mail = imaplib.IMAP4_SSL(SERVER)
mail.login(LOGIN, PASSWORD)
mail.select('INBOX.Test.Subtest', readonly=True)

for i in range(5):
  resp, data = mail.uid('search', '%d:*' % (i+1))
  print i+1, resp, data

And its output:

1 OK ['1 2 4 5']
2 OK ['2 4 5']
3 OK ['4 5']
4 OK ['5']
5 OK ['5']

So the first parameter is interpreted as a sequence number, not as UID. The line "4 OK ['5']" should read "4 OK ['4 5']".

What am I missing?


Solution

  • On closer examination of the RFC 3501 I've came up with an answer:

    resp, data = mail.uid('search', 'ALL', 'UID', '%d:*' % (i+1))
    

    So we are selecting messages with all sequential IDs with UIDs in the range.

    The output of the modified program looks like expected:

    1 OK ['1 2 4 5']
    2 OK ['2 4 5']
    3 OK ['4 5']
    4 OK ['4 5']
    5 OK ['5']