Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get 'Message-ID' using imaplib

Tags:

python

imap

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?.

like image 446
vernomcrp Avatar asked Sep 23 '10 05:09

vernomcrp


4 Answers

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
like image 140
pyfunc Avatar answered Nov 19 '22 08:11

pyfunc


You can try this python code to fetch the header information of all the mails.

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')
like image 38
Avadhesh Avatar answered Nov 19 '22 07:11

Avadhesh


There is much easier method 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!

like image 4
Shreejibawa Avatar answered Nov 19 '22 08:11

Shreejibawa


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]
like image 2
Sgali Avatar answered Nov 19 '22 08:11

Sgali