Searching email body without downloading - IMAP

2.1k views Asked by At

Can I search ALL emails over IMAP without downloading the message(s)?

As specified in 6.4.4 of RFC 3501 IMAP version 4 revision 1 (IMAP4rev1):

The SEARCH command searches the mailbox for messages that match the given searching criteria. Searching criteria consist of one or more search keys. The untagged SEARCH response from the server contains a listing of message sequence numbers corresponding to those messages that match the searching criteria.

The defined search keys are as follows. Refer to the Formal Syntax section for the precise syntactic definitions of the arguments

BODY Messages that contain the specified string in the body of the message.

...so I wonder if I can search inside the body of the email without downloading it first?

1

There are 1 answers

2
axiac On BEST ANSWER

The function imap_search() could help you but have in mind that it needs to be supported by the IMAP server to work.

UPDATE:

This is the small program:

error_reporting(E_ALL);
ini_set('display_errors', '1');

$user = '';         // put your Gmail email address here (including '@gmail.com');
$pass = '';         // put your Gmail password here
$host = 'imap.gmail.com:993';      // Put your IMAP server here with portGmail
$keyword = '';      // put the word you want to find


$mailbox = sprintf('{%s/imap/ssl/user=%s}INBOX', $host, $user);
$query = sprintf('BODY "%s"', $keyword);

$mbox  = imap_open($mailbox, $user, $pass, OP_READONLY);
if ($mbox) {
    $list = imap_search($mbox, $query, SE_UID);
    var_dump($list);
    imap_close($mbox);
}

It may or may not work with your setup. It worked for me with one account on our company mail server. It failed to connect on another server that works fine with my regular email client.

It worked and failed on the same time (!!) with Gmail. Don't ask!