How to get "Message-ID" using imaplib

I am trying to get a unique identifier that does not change while working. I think the UID is not very good. Therefore, I think the β€œMessage-ID” is the right thing, but I don’t know how to get it. I only know imap.fetch (uid, 'XXXX'), does anyone have a solution ?.

+4
source share
4 answers

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 
+6
source

You can try this python code to get the header information of all emails.

 import imaplib import email obj = imaplib.IMAP4_SSL('imap.gmail.com', 993) obj.login('username', 'password') obj.select('folder_name') resp,data = obj.uid('FETCH', '1:*' , '(RFC822.HEADER)') messages = [data[i][1].strip() + "\r\nSize:" + data[i][0].split()[4] + "\r\nUID:" + data[i][0].split()[2] for i in xrange(0, len(data), 2)] for msg in messages: msg_str = email.message_from_string(msg) message_id = msg_str.get('Message-ID') 
+4
source

There is a much simpler way for this ...

 typ, data = obj.fetch(num, '(BODY[HEADER.FIELDS (MESSAGE-ID)])') msg_str = email.message_from_string(data[0][1]) message_id = msg_str.get('Message-ID') print message_id 

Hope this helps!

+1
source
 result, data = imapconnection.uid('search', None, "ALL") # search and return uids instead latest_email_uid = data[0].split()[-1] result, data = imapconnection.uid('fetch', latest_email_uid, '(RFC822)') raw_email = data[0][1] 
+1
source

All Articles