Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrieve/search for emails using message ID through python IMAP

Tags:

python

email

imap

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

like image 908
Hamid Sayeed Avatar asked Aug 30 '26 23:08

Hamid Sayeed


2 Answers

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)
like image 152
Hamid Sayeed Avatar answered Sep 02 '26 06:09

Hamid Sayeed


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.

like image 37
Vladimir Avatar answered Sep 02 '26 06:09

Vladimir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!