无法删除GMAIL PHP API中的标签

时间:2016-08-29 23:15:56

标签: php gmail gmail-api gmail-imap gmail-pop

我正在开展一个项目,其中我有几个与每封电子邮件关联的标签。我想使用gmail PHP API删除标签。我已经按照文档进行了操作,并完成了所有步骤。但是,当我尝试删除标签时,我不知道为什么会出现错误。

这是与项目关联的代码。请帮我解决一下。

  $client_id = 'aoppedisano@tecnavi.com';
  $service_account_name = 'anthony@teak-truck- 130612.iam.gserviceaccount.com';
  $key_file_location = 'anthony.p12';
  $userid_from='aoppedisano@tecnavi.com';
  $client = new Google_Client();
  var_dump($client);
  $client->setScopes(array('https://www.googleapis.com/auth/gmail.modify'));
  $client->setApplicationName("Client_Library_Examples");
  if (isset($_SESSION['service_token'])) {
    $client->setAccessToken($_SESSION['service_token']);
 }
 $key = file_get_contents($key_file_location);
 $cred = new Google_Auth_AssertionCredentials(
  $service_account_name,
  array(
 /*     
    'https://www.googleapis.com/auth/gmail.send',
    'https://www.googleapis.com/auth/gmail.compose',
    'https://www.googleapis.com/auth/gmail.modify',
*/
    'https://www.googleapis.com/auth/gmail.readonly'
 ),
   $key
   );
   //var_dump($cred);
  $cred->sub=$userid_from; //<-- Important!
  $client->setAssertionCredentials($cred);

  if ($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
 }
 $service = new Google_Service_Gmail($client);
 $messageId=$_REQUEST["id"];
 $userId = 'me';
 $optParamsGet = [];
 $optParamsGet['format'] = 'full';
 $message = $service->users_messages->get('me',$messageId,$optParamsGet);
 $labelsToRemove=$_REQUEST['label'];
 $labelsToAdd=[];
 $message=modifyMessage($service,$userId, $messageId, $labelsToAdd,         $labelsToRemove);



    function modifyMessage($service, $userId, $messageId, $labelsToAdd,  $labelsToRemove) {
     $mods = new Google_Service_Gmail_ModifyMessageRequest();
     $mods->setAddLabelIds($labelsToAdd);
     $mods->setRemoveLabelIds($labelsToRemove);
    try {
     $message = $service->users_messages->modify($userId, $messageId, $mods);
     print 'Message with ID: ' . $messageId . ' successfully modified.';
     return $message;
    } catch (Exception $e) {
     print 'An error occurred: ' . $e->getMessage();
   }
 }

1 个答案:

答案 0 :(得分:0)

正如Standard Error Responses中针对Google API所述,403: insufficientPermissions错误代码表示经过身份验证的用户没有足够的权限来执行此请求。

要删除标签,您应该在权限中包含此范围代码:

https://www.googleapis.com/auth/gmail.labels

有关范围的详细信息,请查看Choose Auth Scopes