From the IMAP documentation itself:
IMAP4 message numbers change when the mailbox changes; in particular, after the EXPUNGE command deletes, the remaining messages are renumbered. Therefore, it is highly advisable to use a UID instead of a UID command.
Discussion in SO: About IMAP UID with imaplib
IMAP4.fetch(message_set, 'UID')
Fetch is the best way to get UID messages
And to get the message id you can do something like this. Although not all messages may have a message identifier.
server.select(imap_folder) # List all messages typ, data = server.search(None, 'ALL') # iterate through messages for num in data[0].split(): typ, data = server.fetch(num, '(BODY[HEADER.FIELDS (MESSAGE-ID)])') # parse data to get message id
source share