Search code examples
phpgmail-imap

PHP GMail IMAP Connection Failure


I am using this repo for connecting to the gmail. But its getting error. I hope someone has experience handling this recently.

<?php
    namespace program;

    require_once "php-imap-client/vendor/autoload.php";

    use SSilence\ImapClient\ImapClientException;
    use SSilence\ImapClient\ImapConnect;
    use SSilence\ImapClient\ImapClient as Imap;

    $mailbox = 'imap.gmail.com';
    $username = '[email protected]';
    $password = "wonderland";
    $encryption = Imap::ENCRYPT_SSL;

    // Open connection
    try{
        $imap = new Imap($mailbox, $username, $password, $encryption);
        // You can also check out example-connect.php for more connection options

    }catch (ImapClientException $error){
        echo $error->getMessage().PHP_EOL;
        die(); // Oh no :( we failed
    }

Solution

  • I've had this before too. From the link in the error message you're receiving.

    Allow less secure apps: If you don't use 2-Step Verification, you might need to allow less secure apps to access your account.

    Here's a guide to do so