PHP imap_search not detecting all messages in gmai

2019-04-29 13:22发布

问题:

When I run a very simple imap_search on my GMail inbox, the search returns less messages than it should.

Here is the script that anyone with a GMail account can run.

$host = '{imap.gmail.com:993/imap/ssl}';
$user = 'foo';
$pass = 'bar';

$imapStream = imap_open($host,$user,$pass) or die(imap_last_error());

$messages = imap_search($imapStream,"ALL");

echo count($messages);

imap_close($imapStream);

This returns 39 messages. But, I've got 100 messages in my inbox, some bundled in conversations, some forwarded from another account (SquirrelMail).

Can anyone duplicate these results, and/or tell me what's going on?


Other server strings I've tried, all returning the same results:

{imap.gmail.com:993/imap/ssl/novalidate-cert}
{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX
{imap.gmail.com:993/imap/ssl}INBOX

GMail's IMAP feature support: http://mail.google.com/support/bin/answer.py?hl=en&answer=78761

回答1:

After significant hair loss, I've found the answer. It was a misleading UI.

GMail groups one's messages into "Conversations" by default. These conversations can include archived messages.

So, for example, Bob's inbox looks like there's 4 conversations of 25 messages, which should apparently return 100 inbox messages. In reality, 60 of the messages are in the archive (not the inbox), so the imap_search() returns 40. These messages are magically pulled out of the archive and placed into inbox conversations.

In the Settings->General menu, you can toggle conversation view, which will put all of those naughty archived messages back where they belong, and show your true inbox view.



回答2:

imap_search criteria ALL - return all messages matching the rest of the criteria , so i ask you where is the rest of the criteria ?

You could use imap_sort($imapStream, 'SORTDATE', 0); ( imap_sort - Gets and sorts message numbers by the given parameters imap_sort ) .


Edit , here is some code that goes thru all messages in you're inbox , instead of imap_num_msg , you could use imap_sort as stated before , so you get you're inbox sorted if you like .

<?php
    $imap = imap_open("{mail.yourserver.com:143}INBOX", "username", "password");
    $message_count = imap_num_msg($imap);

    for ($i = 1; $i <= $message_count; ++$i) {
        $header = imap_header($imap, $i);
        $body = trim(substr(imap_body($imap, $i), 0, 100));
        $prettydate = date("jS F Y", $header->udate);

        if (isset($header->from[0]->personal)) {
            $personal = $header->from[0]->personal;
        } else {
            $personal = $header->from[0]->mailbox;
        }

        $email = "$personal <{$header->from[0]->mailbox}@{$header->from[0]->host}>";
        echo "On $prettydate, $email said \"$body\".\n";
    }

    imap_close($imap);
?>


标签: php gmail imap