Search code examples
pythonimap

How to get 'Message-ID' using imaplib


I try to get an unique id that's not change during operation. I think UID is not good. So I think 'Message-ID' is the right thing, But I don't know how to get it. I know just imap.fetch(uid, 'XXXX'), Anyone has a solution?.


Solution

  • From IMAP documentation itself:

    IMAP4 message numbers change as the mailbox changes; in particular, after an EXPUNGE command performs deletions the remaining messages are renumbered. So it is highly advisable to use UIDs instead, with the UID command.

    Discussion at SO : About IMAP UID with imaplib

    IMAP4.fetch(message_set, 'UID')
    

    Fetch is the best way to get the UID of the message

    And to get message ID you could do some thing like this, Although not all messages may have a message id.

    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