'Connection Failure with PHP and GMail IMAP

I have looked at several tutorials and different explanations but although I have enabled imap in gmai, enabled the permission for insecure activities, my connection string is

imap_open('{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX', 'email', 'pwd')

and I have not activated the two-factor authentication I still have the same error.

Cannot connect to Gmail: Can not authenticate to IMAP server: [ALERT] Please log in via your web browser

this is all the code

<?php
    
    /* Connecting Gmail server with IMAP */
    $connection = imap_open('{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX', 'email', 'pwd') or die('Cannot connect to Gmail: ' . imap_last_error());

    /* Search Emails having the specified keyword in the email subject */
    $emailData = imap_search($connection, 'SUBJECT "Article "');
    
    if (! empty($emailData)) {
        ?>
        <table>
        <?php
        foreach ($emailData as $emailIdent) {
            
            $overview = imap_fetch_overview($connection, $emailIdent, 0);
            $message = imap_fetchbody($connection, $emailIdent, '1.1');
            $messageExcerpt = substr($message, 0, 150);
            $partialMessage = trim(quoted_printable_decode($messageExcerpt)); 
            $date = date("d F, Y", strtotime($overview[0]->date));
            ?>
            <tr>
                    <td style="width:15%;"><span class="column"><?php echo $overview[0]->from; ?></span></td>
                    <td class="content-div"><span class="column"><?php echo $overview[0]->subject; ?> - <?php echo $partialMessage; ?></span><span class="date"><?php echo $date; ?></span></td>
            </tr>
            <?php
        } // End foreach
        ?>
        </table>
        <?php
    } // end if
    
    imap_close($connection);
}
?>

I don't understand why...



Solution 1:[1]

IMAP={imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX

$message = imap_fetchbody($connection, $emailIdent, 1);

https://accounts.google.com/DisplayUnlockCaptcha - go to this url and enable it.

Go to gmail Top right - settings

See all settings - under - quick settings

Forwarding and pop/imap

Enable Imap - save changes

Next go to manage your google account - security

Less secure app access - On

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1