Parsing the Message-ID header returned by imaplib

I am extracting messageid from emails in Gmail via IMAP.

This code:

messageid = m.fetch(num, '(BODY[HEADER.FIELDS (MESSAGE-ID)])')
print messageid

returns this:

[('1 (BODY[HEADER.FIELDS (MESSAGE-ID)] {78}', 'Message-ID: <actualmessageid@mail.mail.gmail.com>\r\n\r\n'), ')']

How can I parse only the actual message id?

+3
source share
2 answers

You can also achieve what you want using the emailmodule HeaderParser.parsestr()function (the same API as Parser, but not worried about the body of the message) and parseaddr()function .

>>> from email.parser import HeaderParser
>>> from email.utils import parseaddr

>>> hp = HeaderParser()

>>> response = [('1 (BODY[HEADER.FIELDS (MESSAGE-ID)] {78}',
                 'Message-ID: <actualmessageid@mail.mail.gmail.com>\r\n\r\n'), ')']

>>> header_string = response[0][1]

>>> header_string
'Message-ID: <actualmessageid@mail.mail.gmail.com>\r\n\r\n'

>>> header = hp.parsestr(header_string)

>>> header
<email.message.Message instance at 0x023A6198>

>>> header['message-id']
'<actualmessageid@mail.mail.gmail.com>'

>>> msg_id = parseaddr(header['message-id'])

>>> msg_id
('', 'actualmessageid@mail.mail.gmail.com')

>>> msg_id[1]
'actualmessageid@mail.mail.gmail.com'

In this way:

from email.parser import HeaderParser
from email.utils import parseaddr

hp = HeaderParser()

def get_id(response):
    header_string = response[0][1]
    header = hp.parsestr(header_string)
    return parseaddr(header['message-id'])[1]

response = [('1 (BODY[HEADER.FIELDS (MESSAGE-ID)] {78}',
             'Message-ID: <actualmessageid@mail.mail.gmail.com>\r\n\r\n'), ')']


print(get_id(response))

returns:

actualmessageid@mail.mail.gmail.com
+7
source

From RFC 1036, 822 :

To comply with RFC-822, the Message Identifier must be in the format: <unique @full_domain_name>

, < > .

, , , < , , > .

( ?), , -

 # Note: my list does not end with , ")"]
 messageparts = [('1 (BODY[HEADER.FIELDS (MESSAGE-ID)] {78}', 
                  'Message-ID: <actualmessageid@mail.mail.gmail.com>\r\n\r\n')]

 for envelope, data in messageparts:
        # data: the part with Message-ID in it
        # data.strip(): Newlines removed
        # .split("<"): Break in 2 parts, left of < and right of <. Removes <
        # .rstrip(">") remove > from the end of the line until there is 
        # no > there anymore;
        # "x>>>".rstrip() -> "x"
        print "The message ID is: ", data.strip().split("<")[1].rstrip(">")

    # Short alternative version:
    messageids = [data.strip().split("<")[1].rstrip(">") \
                  for env,data in messageparts]
    print messageids

:

The message ID is:  actualmessageid@mail.mail.gmail.com
['actualmessageid@mail.mail.gmail.com']

, '\', , , .

0

Source: https://habr.com/ru/post/1796521/


All Articles