Are there alternative methods to securely authenticate users against IMAP without exposing passwords in the source code?

One alternative method to securely authenticate users against IMAP without exposing passwords in the source code is to use OAuth authentication. This involves obtaining an access token from the user and using it to authenticate with the IMAP server. This way, the password is not stored in the source code and the authentication process is more secure.

<?php

// Include the Google API Client Library
require_once 'vendor/autoload.php';

// Set up the OAuth client
$client = new Google_Client();
$client->setAuthConfig('client_secret.json');
$client->addScope(Google_Service_Gmail::MAIL_GOOGLE_COM);

// Authenticate the user
if ($client->getAccessToken()) {
    $accessToken = $client->getAccessToken();
    
    // Use the access token to authenticate with the IMAP server
    $imapStream = @imap_open('{imap.gmail.com:993/imap/ssl}INBOX', 'user@gmail.com', $accessToken['access_token']);
    
    if ($imapStream) {
        echo 'Authenticated successfully!';
        imap_close($imapStream);
    } else {
        echo 'Authentication failed.';
    }
} else {
    $authUrl = $client->createAuthUrl();
    echo 'Please <a href="' . $authUrl . '">authorize access</a> before proceeding.';
}
?>