Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

imap_check throwing notice when mailbox is empty

So I've recently started my first real job (yay!) and I'm working on an email checker.

It's working great, no errors... provided there are emails.

$mbox = imap_open("{.../pop3/novalidate-cert}INBOX","[email protected]","...");
$inbox = imap_check($mbox);

The above code works just fine when there are emails in the inbox, but if there aren't I get this error at the end of the page:

Notice: Unknown: Mailbox is empty (errflg=1) in Unknown on line 0

No amount of error suppression seems to be able to stop this from being thrown, other than error_reporting(E_ALL^E_NOTICE), which I'd rather not use (for once!)

Can anything be done?

Upvotes: 3

Views: 3681

Answers (2)

Dominique
Dominique

Reputation: 1119

I just discovered that calling the imap_errors() function suppresses the notice exception.

So the only thing you need to do is add this somewhere in your code:

$errors = imap_errors();

What you do with the $errors variable afterwards is up to you.

Upvotes: 8

SamV
SamV

Reputation: 7586

I think this may be a PHP discrepancy.

Check out this IMAP library https://github.com/barbushin/php-imap. I have used this in a project that has imported thousands of emails with no issues.

protected function initImapStream() {
    $imapStream = @imap_open($this->imapPath, $this->login, $this->password);
    if(!$imapStream) {
        throw new ImapMailboxException('Connection error: ' . imap_last_error());
    }
    return $imapStream;
}

The @ error suppression operator is used, I guess that this is the workaround.

Source: https://github.com/barbushin/php-imap/blob/master/src/ImapMailbox.php#L48

Edit: Turns out you can turn this notice off via an option. Quote from http://php.net/manual/en/function.imap-open.php#73514

you can avoid this message :

Warning: (null)(); Mailbox is empty (errflg=1) in Unknown on line 0

by specified the option OP_SILENT to imap_open.

Upvotes: 7

Related Questions