Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python IMAP search for partial subject

Tags:

python

imap

I'm trying to fetch all emails whose subject starts with "New Order" but I can't seem to figure it out. Currently I can search for an exact match with a setup like so...

result, data = M.uid('search', None, '(HEADER Subject "Subject Here")')

However this won't retrieve any messages that aren't an exact match. How would I go about doing a partial match?

If it matters I am talking to gmail's imap server(s).

Thanks

like image 914
Kazurik Avatar asked Nov 15 '12 18:11

Kazurik


2 Answers

According to the IMAP RFC SEARCH should do all of its matching as substring matches:

In all search keys that use strings, a message matches the key if the string is a substring of the field. The matching is case-insensitive.

Therefore, a search

M.uid('search', None, 'HEADER Subject "New Order"')

should match all messages where New Order occurs anywhere in the subject. If it is not, you should notify Google that their server does not implement IMAP properly. In the meantime you might try using the SUBJECT key as in

M.uid('search', None, 'SUBJECT "New Order"')

Also, according to Google's IMAP extension documentation you might be able to use the X-GM-RAW key and a gmail search string as in

M.uid('search', None, r'X-GM-RAW "subject:\"New Order\""')
like image 193
Geoff Reedy Avatar answered Nov 15 '22 14:11

Geoff Reedy


This worked for me:

mail.uid('search', None, r'(X-GM-RAW "subject:\"New Order\"")')
like image 4
user2216945 Avatar answered Nov 15 '22 14:11

user2216945