Thursday, 18 October 2012

PHP: Workaround for the mailbox is empty imap error

If you are in the process of learning how to use the PHP imap* family of functions in order to manage a remote mailbox, here is a little hint to let you get away with the first annoying error warning you are likely to run into.

So here is how the story goes. You open am empty mailbox. Do something with it and then when you close it you get a PHP warning like :

Notice (8): Unknown: Mailbox is empty (errflg=1) [Unknown, line ??]

I have read many ways for handling this. The bottom line is that this is only a warning and due to the nature of the PHP imap functions, it will eventually be flashed when you call imap_close() or when your script exits. Fortunately each call to imap_errors() flashes the internal error log, so a simple way to avoid the entire hassle would be to code something like ...

    function connect()
        $mailBoxx = @imap_open($this->server, $this->username, $this->password);

        if ($mailBox) {
            // call this to avoid the mailbox is empty error message
            if (imap_num_msg($mailBox) == 0)
                $errors = imap_errors();
            return TRUE;
        // imap_errors() will contain the list of real errors
        return FALSE;