barbushin / php-imap

Manage mailboxes, filter/get/delete emails in PHP (supports IMAP/POP3/NNTP)
MIT License
1.65k stars 459 forks source link

#571: Improve ConnectionException handling #652

Closed Sebbo94BY closed 2 years ago

Sebbo94BY commented 2 years ago

This change solves the issue, that the original IMAP connect error gets masked.

ConnectionException::getErrors($select = 'first') is a new function, which allows to get either all IMAP errors, only the first or last reported error.

ConnectionException::getMessage() is still simply returning a string. This string contains now all IMAP errors as JSON encoded format. The implementation allows further options for the future, if necessary.

Example code to test:

<?php
    require_once __DIR__.'/../vendor/autoload.php';

    use PhpImap\Exceptions\ConnectionException;
    use PhpImap\Mailbox;

    $mailbox = new Mailbox(
        '{imap.gmail.com:993/imap/ssl}INBOX', // IMAP server and mailbox folder
        'some@gmail.com', // Username for the before configured mailbox
        'wrongPassword', // Password for the before configured username
        __DIR__, // Directory, where attachments will be saved (optional)
        'US-ASCII' // Server encoding (optional)
    );

    try {
        $mail_ids = $mailbox->searchMailbox('ALL');
    } catch (ConnectionException $ex) {
        // Get first reported IMAP error
        exit('IMAP connection failed: '.$ex->getErrors()); // default behaviour
        exit('IMAP connection failed: '.$ex->getErrors('first'));

        // Get last reported IMAP error
        exit('IMAP connection failed: '.$ex->getErrors('last'));

        // Get all reported IMAP errors (Array)
        exit('IMAP connection failed: '.implode(",", $ex->getErrors('all')));

        // Get all reported IMAP errors (JSON encoded string)
        exit('IMAP connection failed: '.$ex->getMessage());
    } catch (Exception $ex) {
        exit('An error occured: '.$ex->getMessage());
    }

Fixes #571.