Search code examples
pythonemailimapimaplib

Why does an 'IMAP search by header' fail when the header value is given by a variable, not a string?


I can get the uid of an email that has a certain header value like this:

    res, tmp = self.mail.uid('search', None, '(HEADER Message-ID "<123.456.789@localhost>")')

Then, tmp becomes

[b'2993']

But I get that Message-ID value from a file, store the value into a variable(msg_ID), and give the msg_ID variable as an input.

When I try the above one like:

tmp = "<123.456.789@localhost>"
res, tmp = self.mail.uid('search', None, '(HEADER Message-ID tmp)')

tmp returns an empty list

[b'']

, which means that it failed to search the target email.

How can I give an appropriate input with a variable?


Solution

  • In your example you're sending the actual string tmp - it won't be expanded inside the string magically.

    You also lack the other formatting around the string, which should be added to make them identical:

    '(HEADER Message-ID "' + tmp + '")'
    

    That way your strings will actually be identical and it should work as you expect. As your code is written you're just asking for the email with the Message-ID literally set to tmp.