Unable to handle errors in PHP IMAP

17 Views Asked by At

I am using PHP IMAP library for my gmail account. Its working fine but when app password wrong its giving fatal error and stopping the script. I have tried to try and catch method but no luck.

 try {
        
    $mailbox = new Mailbox($hoststring, '[email protected]', "examplepassword", false);
    try {
        $mailbox->switchMailbox("INBOX");  //its stopping on this line  
        $mail_ids = $mailbox->searchMailbox('ALL');
    } catch (ConnectionException $ex) {
       $error = $ex->getMessage();
        echo $error;
    } catch (Exception $ex) {
        $error = $ex->getMessage();
        echo $error;
    }
                
 }catch (ConnectionException $ex) {
        $error = $ex->getMessage();
        echo $error;
        
    }catch (Exception $ex) {
        $error = $ex->getMessage();
        echo $error;
       
}

Its getting stopped on below line

$mailbox->switchMailbox("INBOX");  

and error is

PHP Fatal error: Uncaught PhpImap\Exceptions\ConnectionException: ["Can not authenticate to IMAP server: [AUTHENTICATIONFAILED] Invalid credentials (Failure)"] in /home/example/postmaster.example.com/dashboard/crons/imap/vendor/php-imap/php-imap/src/PhpImap/Imap.php:712

Here is the function which is generating error

public static function open(
        string $mailbox,
        string $username,
        string $password,
        int $options = 0,
        int $n_retries = 0,
        array $params = []
    ) {
        if (\preg_match("/^\{.*\}(.*)$/", $mailbox, $matches)) {
            $mailbox_name = $matches[1] ?? '';

            if (!\mb_detect_encoding($mailbox_name, 'ASCII', true)) {
                $mailbox = static::encodeStringToUtf7Imap($mailbox);
            }
        }

        \imap_errors(); // flush errors

        $result = @\imap_open($mailbox, $username, $password, $options, $n_retries, $params);

        if (!$result) {
            throw new ConnectionException(\imap_errors() ?: []);///this error
        }

        return $result;
    }

I have tried to get answer from repo but no luck, Let me know if anyone here can help me for the same. Thanks!

0

There are 0 best solutions below