pythonimapimapclient

Python IMAPClient - fetching UID


I am using IMAPClient in my Django email client, and currently I am trying to fetch UIDs of the first fifty messages in a given mailbox by the following code:

server = IMAPClient(HOST, use_uid=True, ssl=True)
server.login(USERNAME, PASSWORD)
server.select_folder(folder_name)
messages = server.search(['NOT DELETED', '1:50']) 
response = server.fetch(messages, ['UID'])

I would expect then to fetch the unique message identifier by the following command:

for data in response.items():
    data[b'UID']

but I end up with keyerror - data has no key named 'UID'. What am I doing wrong? What is the correct way of getting message UIDs via IMAPClient ?


Solution

  • IMAPClient uses UIDs by default. This means that by default, the message ids returned by search() are UIDs. There is no need to query for UIDs separately.

    The use_uid argument to the IMAPClient constructor and the use_uid attribute can be used to switch the behaviour. When use_uid is True all methods that accept or return message ids work with UIDs. fetch() also includes the message sequence as a SEQ item.

    When use_uid is False, fetch() accepts message sequences but you can query for UIDs.

    Example:

    server = IMAPClient(HOST, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)
    server.select_folder(folder_name)
    
    messages = server.search(...)
    # messages contains UIDs
    
    r = server.fetch(messages, [...])
    for uid, data in r.items():
        print(uid, data[b'SEQ'])   # show UID & message sequence
    
    server.use_uid = False
    
    messages = server.search(...)
    # messages contains sequence numbers (not UIDs)
    
    r = server.fetch(messages, ['UID'])
    for seq, data in r.items():
        print(seq, data[b'UID'])   # show message sequence & UID
    

    More here: https://imapclient.readthedocs.io/en/2.1.0/concepts.html#message-identifiers