How to filter/search for emails with a custom header field using Python imaplib?

208 views Asked by At

I want to filter emails for the presence of a specific custom header field, e.g. "X-my-header-field: my-header-value". I am using Python's imaplib. I unsuccessfully tried the search method: rv, data = mailbox.search(None, "X-my-header-field", 'my-header-value').

Does anybody have an idea or hint how to accomplish this? The idea is to filter the emails before downloading it from the server.

2

There are 2 answers

0
Jonas On

I found the answer with the hint of Vikas reply and reading RFC 9051:

M.search(None, '(HEADER "X-my-header-field" "my-header-value")')
1
Vikas kashyap On
mail.list()
mail.select("inbox") # connect to inbox.
result, data = mail.search(None, '(FROM "anjali sinha" SUBJECT "test")' )
ids = data[0] # data is a list.
id_list = ids.split() # ids is a space separated string