0

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.

Jonas
  • 2,974
  • 4
  • 24
  • 23

2 Answers2

1
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
  • Thank you Vikas for your reply. I tried it your way: mail.search(None, 'X-my-header-field "my-header-value")') but I still get a runtime error: File "/usr/lib/python3.9/imaplib.py", line 1055, in _command_complete raise self.error('%s command error: %s %s' % (name, typ, data)) imaplib.error: SEARCH command error: BAD [b'Could not parse command'] Do you have any idea? – Jonas Dec 19 '22 at 10:30
0

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")')
Jonas
  • 2,974
  • 4
  • 24
  • 23