PHP Command Line Application || That make request to Gmail API

TIJ Tech Private Limited
5 min readJan 20, 2021

For more details and informations, please refer the YouTube Video.

Video URL: https://youtu.be/ljuO9NOX7z8

Overview

In this tutorial, we will teach everything that we need to know about PHP command line application that will make request to Gmail API.

Steps to be followed!

  1. Download and Install XAMPP
For Windows and Linux:
https://www.apachefriends.org/download.html

After installing XAMPP, open any browser and type “mail quickstart php” and then click on php quickstart Gmail API.

After that we get the Gmail API Page.

Step 1: Turn on the Gmail API.

Before turning “ON” the Gmail API, let us see the prerequisites.

Download and Install Composer

For downloading composer:
https://getcomposer.org/download/

After installing composer, we are going to Enable the Gmail API. Click next, then click on Download Client Configuration.

Then go to the download folder and copy the downloaded file into XAMPP file:

Path: 
Local Disk (C:) >>> xampp >>> htdocs >>> dashboard >>> Create your Working Directory here (Eg: api) >>> Paste the downloaded file here.

Step 2: Install the Google Client Library.

$ composer require google/apiclient:^2.0

Copy the above command code, and open the command prompt (cmd) on the path of your working directory.

Then paste the code on the cmd and click on Enter. The installation of google client library will start and it will take some time to install it.

Step 3: Set up the sample.

<?php
require __DIR__ . '/vendor/autoload.php';

if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}

/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Gmail API PHP Quickstart');
$client->setScopes(Google_Service_Gmail::GMAIL_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');

// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}

// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));

// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);

// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}


// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Gmail($client);

// Print the labels in the user's account.
$user = 'me';
$results = $service->users_labels->listUsersLabels($user);

if (count($results->getLabels()) == 0) {
print "No labels found.\n";
} else {
print "Labels:\n";
foreach ($results->getLabels() as $label) {
printf("- %s\n", $label->getName());
}
}

Copy the above codes into your working directory by creating a new file named as quickstart.php.

Then next, copy the “_DIR_ .” inside the quickstart.php file and paste it into the credential function and type “/” just before “credentials.json” and save the file.

Step 4: Run the sample.

Run the sample using the command on your working directory by using command prompt.

$ php quickstart.php

After that copy the link that is shown in the command prompt and paste it on any browser. Then choose any account to sign in.

Then click on the allow button to grant the quickstart permission.

Then finally copy the code given after granting permission for the quickstart.

And paste it on the working directory command prompt, where the quickstart.php file is being compiled.

Finally, we will see the Gmail feature.

That’s all for this tutorial. Hope this tutorial documentation was helpful. Thank you everyone.

--

--