Search code examples
phpimap

PHP - Error in IMAP command STORE: Invalid messageset


I'm using imap with php and I found this error:

Unknown: IMAP protocol error: Error in IMAP command STORE: Invalid messageset (0.001 + 0.000 secs). (errflg=2)

This happens only with some mailboxes (ex. one hosted on misterdomain.eu).

The error occurs at the end of the script, after imap_close().

This is the simple code. If you have any suggest (far to my first problem), is really accepted.

$inbox = imap_open($hostname,$username,$password) or die('Cannot connect: ' . imap_last_error());
$emails = imap_search($inbox,'SINCE "'.date("d-M-y",strtotime("-3 days")).'"',SE_UID);

if($emails) {
    rsort($emails);
    foreach($emails as $email_number) {

        echo "<h1>".$email_number."</h1>";
        $overview = imap_fetch_overview($inbox,$email_number, FT_UID);

        if($overview[0]->seen)
            imap_clearflag_full($inbox,$email_number,"//Seen");
        else
            imap_clearflag_full($inbox,$email_number,"//Unseen");

        $structure = imap_fetchstructure($inbox,$email_number, FT_UID);

        if(isset($structure->parts)){
            $flattenedParts = flattenParts($structure->parts);
            echo "<pre>";
            print_r($flattenedParts);
            echo "</pre>";
            echo "</br>";           
            getmsg($inbox, $email_number);

            echo "<p>".htmlspecialchars_decode(utf8_decode($plainmsg))."</p>";
        }else{
            $string_email = utf8_decode(imap_body($inbox, $email_number, FT_UID));
            $string_email= strip_tags($string_email);
            $string_email = html_entity_decode($string_email,ENT_QUOTES);
            echo "<p>".$string_email."</p>";
        }

    }
} 
imap_close($inbox);

Solution

  • You are searching and fetching using UIDs, but storing using message sequence numbers. These ways of numbering the messages don't match, so you are sending invalid message numbers to store. Add the approriate ST_UID flag to imap_clearflag_full.

    Also, the system flags use backslashes, not forward slashes: '\\Seen'. \Unseen isn't a defined flag. You probably want to add the \Seen flag instead.