Search code examples
pythonemailsearchimapimaplib

Find messages by sender IMAP.search()


I use the imaplib library to work with emails. I want to find all emails from one person. The next code doesn't work for all messages:

    typ, data = con.search(None, 'FROM "name.surname@testmail.com"')

sometimes I need to set something like this to find that messages:

    typ, data = con.search(None, 'FROM "Surname, Name"')

and I cannot find a message by email. If I understand correct, it's only for messages in html format.

    print(message['From'])
    print(type(message['From']))

That code will print next:

    "Surname, Name" <name.surname@testmail.com>
    <class 'str'>

Why search function doesn't search in this string all possible mentions? Doesn't it work like a normal string search? How should I search, if I want to find all messages with email '@testmail.com', not from a specific person?


Solution

  • I have found an answer here: IMAP search for email address in the from field

    Just use next as a filter:

    (HEADER FROM "name.surname@testmail.com")