0

in imaplib, mail.search requires a criterion, see documentation https://docs.python.org/2/library/imaplib.html and the criterion options https://gist.github.com/martinrusev/6121028

However, I need to be able to use a more generalized search. A set of files is sent from various senders, with various file names. In outlook, I can just type .xlsx to find any emails with attachments or .xlsx. also, searching for 'username@domain.com' would return all the emails to, from, or ccing them. How can I build a similar search function in python using imap?

For this SPECIFIC build, it should be possible with nested if, else, and try blocks. But im looking for something more generalized just to see if there is a better way.

What im trying to accomplish if there isnt

provide two emails, which must be present in either from, or cc, but not in both (sometimes the email arrives from sender 1 with sender 2 cced, sometimes it is sent from 1 to 2, who then forwards to my team). And there needs to be a .xlsx file attached.

AlbinoRhino
  • 467
  • 6
  • 23
  • IMAP search is just not that flexible. You should start just by doing `UID SEARCH BODY ".xlsx"` to see if it'll even do a partial match to find xlsx files. – Max Mar 12 '20 at 19:19

1 Answers1

1

https://github.com/ikvk/imap_tools

Lib implements all search logic described in rfc3501.

You can use imap_tools itself and its query builder separately.

Example:

import datetime
from imap_tools import MailBox, OR
with MailBox('imap.mail.com').login('test@mail.com', 'password', 'INBOX') as mailbox:
    for msg in mailbox.fetch(OR(text='hello', date=datetime.date(2000, 3, 15))):
        print(msg.uid, msg.subject)

See lib docs for more.

Vladimir
  • 6,162
  • 2
  • 32
  • 36