Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IMAP criteria with multiple ORs

I am using gmail's IMAP API to search for mails.

I use the 'OR' criteria to search for different keywords. This works well if I go one level only, i.e. something like

'UID SEARCH OR (FROM "[email protected]") (TO "[email protected]")'

however, it does not work when I try a longer expression like

criteria OR criteria OR criteria or criteria

which translates to (as far as I understand the syntax)

'UID SEARCH OR ( OR (FROM "[email protected]") (TO "[email protected]")) ( OR (FROM "[email protected]") (TO "[email protected]"))'

to make it clear I basically want all messages that are either sent from or sent to ANY of a given list of emails

The error I get from the libray is

[ 'A34', 'BAD', 'Could', 'not', 'parse', 'command' ]

any suggestions?

like image 964
forste Avatar asked Oct 09 '12 23:10

forste


3 Answers

Do not use parenthesis.

IMAP uses polish notation which does not need them:

UID SEARCH OR OR FROM [email protected] TO [email protected] OR FROM [email protected] TO [email protected]

There are cases where parenthesis are needed (as IMAP AND operator can take more than 2 operands): https://www.limilabs.com/blog/imap-search-requires-parentheses

like image 175
Pawel Lesnikowski Avatar answered Nov 06 '22 11:11

Pawel Lesnikowski


So if you have N expressions that you want to "OR" together, you would prefix those N expressions by N-1 "OR"s.

In Perl, for example, that would be:

$search = join " ", ("OR") x (@exprs - 1), @exprs;
like image 22
Waxrat Avatar answered Nov 06 '22 09:11

Waxrat


Just to clarify Pawel's answer (posting since I lack the points to comment), as I didn't quite pick up the nuance:

OR is a prefix operator and can only take two operands (not more). So this translates into:

UID SEARCH OR FROM "[email protected]" TO "[email protected]"

If you have more than two, you need to add an OR: e.g., 3 operands

UID SEARCH OR OR FROM "[email protected]" TO "[email protected]" FROM "[email protected]"

e.g., 4 operands

UID SEARCH OR OR OR FROM "[email protected]" TO "[email protected]" FROM "[email protected]" TO "[email protected]"

In other words, for four operands either: Pawel's answer of :

OR (OR x x) (OR x x)

or what I outlined above:

(OR (OR (OR x x) x) x)

Should work.

like image 1
healthybodhi Avatar answered Nov 06 '22 11:11

healthybodhi