'Google Gmail API - How to login programatically?

I'm looking to write a PHP script that scans my gmail inbox, and reads unread emails. There needs to be NO user interaction. This has to happen on a cronjob that executes a PHP file.

Is this even possible with the API? Googles documentation is absolutely terrible, and no-where does there seems to be any examples that allow you to authorize a log in programatically. They always require a user to physically press the allow button on an oauth request.

Has anybody got experience in trying to simply login and list your messages, without the need of human interaction?



Solution 1:[1]

client login

I think what you are trying to ask here is how to login to the api using your login and password. The anwser is you cant this was called client login and google shut down that option in 2015. You have not choice but to use the Oauth2 if you want to connect to the gmail api

service accounts

Normally i would say that you should use a service account. However service accounts only work with gmail if you have a gsuite account in which case you can set up domain wide delegation's here

// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    return getServiceAccountClient();
}
/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
 * Scopes will need to be changed depending upon the API's being accessed. 
 * array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function getServiceAccountClient() {
    try {   
        // Create and configure a new client object.        
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope([YOUR SCOPES HERE]);
        return $client;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

oatuh2

In the event that you are not using gsuite. Then what you can do is authenticate your code once. Make sure to request off line access. A refresh token will be returned to you. If you save this refresh token you can then use that refresh token at anytime to request a new access token. In the example below you can see how the refresh token was simply stored in a session varable you could store it in a file and read from that when ever you need.

function getOauth2Client() {
    try {

        $client = buildClient();

        // Set the refresh token on the client. 
        if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
            $client->refreshToken($_SESSION['refresh_token']);
        }

        // If the user has already authorized this app then get an access token
        // else redirect to ask the user to authorize access to Google Analytics.
        if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {

            // Set the access token on the client.
            $client->setAccessToken($_SESSION['access_token']);                 

            // Refresh the access token if it's expired.
            if ($client->isAccessTokenExpired()) {              
                $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
                $client->setAccessToken($client->getAccessToken()); 
                $_SESSION['access_token'] = $client->getAccessToken();              
            }           
            return $client; 
        } else {
            // We do not have access request access.
            header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
        }
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

code ripped from Oauth2Authentication.php

smtp

You mentioned that you want to use the gmail api but have you considered going directly though the mail server? This would allow you to use login and password. or oauth -> Imap-smtp

Solution 2:[2]

You need to use three-legged OSuth, that is OAuth where the end-user (owner of the gmail account), logs in and authorizes your app to read their email. There is no other way to access a user's Gmail account via the API except with three-legged OAuth.

The end user needs to click on the first time. Once your app has received consent from the end user, the app can access the Gmail API on behalf of the user in the future without clicks. I find this documentation the clearest, look for grantOfflineAccess().

You could copy and paste a simple JavaScript Frontend from the documentation that allows you to do the log in, and write your backend logic in PHP.

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 DaImTo
Solution 2 user835611