retrieve/search for emails using message ID through python IMAP
Asked Answered
R

2

5

Is there a way to retrieve/search for emails using message ID through python IMAP programmatically.I want to extract attachments of the mail using message ID. Any help would be much appreciated.

Thank you

Rationality answered 25/9, 2018 at 12:34 Comment(3)
What have you tried so far?Martyr
Is there a way ...? Yes. But please show what you have tried....Effie
SEARCH HEADER is your friend, however it is badly implemented or broken on a lot of servers.Litmus
R
11

Thank you all for coming up to help me . I got it done finally. I was searching for a way to get the attachments of a mail with the given Message ID , I didn't know how to specify the search command with the message ID in the HEADER option or any other search option.

I feel it can be helpful to someone like me who is new to IMAP and wants to similar task finally, I got it through this search command :

    #message id
    mid = '<CACDWeWHLGKbEHR-jMmx8da9QzkpPxC7Dizy6T4fm2V30JoHMuw@mail.gmail.com>'

    #the search command
    typ, data = imapSession.search(None, '(HEADER Message-ID "%s")' % mid)
Rationality answered 26/9, 2018 at 8:6 Comment(0)
S
3

You may use imap_tools package: https://github.com/ikvk/imap_tools

If you want to find message by Message-ID:

from imap_tools import MailBox, A, H

with MailBox('imap.mail.com').login('[email protected]', 'pwd', 'INBOX') as mailbox:
    for msg in mailbox.fetch(A(header=H('Message-ID', '[email protected]'))):
        print(msg.date, msg.headers['message-id'])

But often, most likely you need an "uid"

https://www.rfc-editor.org/rfc/rfc3501#section-2.3.1.1

some examples:

with MailBox('imap.mail.com').login('[email protected]', 'pwd', 'INBOX') as mailbox:

    # COPY all messages from current folder to folder1, *by one
    for msg in mailbox.fetch():
        res = mailbox.copy(msg.uid, 'INBOX/folder1')

    # DELETE all messages from current folder
    mailbox.delete(mailbox.uids())

    # FLAG unseen messages in current folder as Answered and Flagged
    flags = (imap_tools.StandardMessageFlags.ANSWERED, imap_tools.StandardMessageFlags.FLAGGED)
    mailbox.flag(mailbox.uids(AND(seen=False)), flags, True)

Regards, imap_tools author.

Scant answered 9/10, 2019 at 13:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.