<?phprequire__DIR__.'/vendor/autoload.php';useGoogle\Client;useGoogle\Service\Gmail;functiongetLabels(){$client=newClient();$client->setApplicationName('Gmail API PHP Quickstart');$client->setScopes('https://www.googleapis.com/auth/gmail.readonly');$client->setAuthConfig("client_secret.json");$client->setAccessType('offline');$client->setPrompt('select_account consent');$tokenPath="token.json";if(file_exists($tokenPath)){$accessToken=json_decode(file_get_contents($tokenPath),true);$client->setAccessToken($accessToken);}elseif($authCode=$_GET["code"]){// 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)){thrownew\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()));}// 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();header("Location: ".$authUrl);}}try{$service=newGmail($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());}}}catch(\Exception$e){echo"Message: ".$e->getMessage();}}getLabels();