(403)权限不足,用于在gmail api上发送电子邮件

时间:2015-07-21 18:12:54

标签: php google-api gmail send http-status-code-403

我能够检索带有身份验证的电子邮件,以便阅读google api。我跟着quick start guid,在设置客户端并将其链接到client_secret.json文件后能够阅读电子邮件。

到目前为止我的工作如下:

<?php
require 'google-api-php-client/src/Google/autoload.php';

define('APPLICATION_NAME', 'Gmail API Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/gmail-api-quickstart.json');
define('CLIENT_SECRET_PATH', 'client_secret.json');
define('SCOPES', implode(' ', array(
  Google_Service_Gmail::GMAIL_READONLY)
));

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
  $client = new Google_Client();
  $client->setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES);
  $client->setAuthConfigFile(CLIENT_SECRET_PATH);
  $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = file_get_contents($credentialsPath);
  } 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->authenticate($authCode);

    // Store the credentials to disk.
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, $accessToken);
    printf("Credentials saved to %s\n", $credentialsPath);
  }
  $client->setAccessToken($accessToken);

  // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
    $client->refreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, $client->getAccessToken());
  }
  return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
  $homeDirectory = getenv('HOME');
  if (empty($homeDirectory)) {
    $homeDirectory = getenv("HOMEDRIVE") . getenv("HOMEPATH");
  }
  return str_replace('~', realpath($homeDirectory), $path);
}

// 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);

//$results = $service->users_messages->get('denverwebsiterepair@gmail.com', '14eadd821012b3ed');
$optParams['maxResults'] = 5; 
$optParams['labelIds'] = 'INBOX'; 
$messages= $service->users_messages->listUsersMessages('me', $optParams); 
$list = $messages->getMessages(); 
$messageId = $list[0]->getId(); 

$optParamsGet = []; 
$optParamsGet['format'] = 'full'; 
$message = $service->users_messages->get('me', $messageId, $optParamsGet); 
$messagePayload = $message->getPayload(); 
$headers = $message->getPayload()->getHeaders(); 
$part = $message->getPayload()->getParts(); 

$body = $part[0]['body']; 
$rawData = $body->data; 
$decodeMessage = base64_decode($rawData); 

// THIS IS THE MESSAGE BODY I CAN GET

echo $decodeMessage; 

让我感到困惑的是,当我尝试以下尝试发送邮件时,根据Google说明,我收到错误:

Error calling POST https://www.googleapis.com/gmail/v1/users/me/messages/send: (403) Insufficient Permission

我所做的就是在底部添加一个更改:

<?php
require 'google-api-php-client/src/Google/autoload.php';

define('APPLICATION_NAME', 'Gmail API Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/gmail-api-quickstart.json');
define('CLIENT_SECRET_PATH', 'client_secret.json');
define('SCOPES', implode(' ', array(
  Google_Service_Gmail::GMAIL_READONLY)
));

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
  $client = new Google_Client();
  $client->setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES);
  $client->setAuthConfigFile(CLIENT_SECRET_PATH);
  $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = file_get_contents($credentialsPath);
  } 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->authenticate($authCode);

    // Store the credentials to disk.
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, $accessToken);
    printf("Credentials saved to %s\n", $credentialsPath);
  }
  $client->setAccessToken($accessToken);

  // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
    $client->refreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, $client->getAccessToken());
  }
  return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
  $homeDirectory = getenv('HOME');
  if (empty($homeDirectory)) {
    $homeDirectory = getenv("HOMEDRIVE") . getenv("HOMEPATH");
  }
  return str_replace('~', realpath($homeDirectory), $path);
}

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

//------------ MY CHANGES HERE ---------------

$service = new Google_Service_Gmail($client);

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

try {
    $msg = new Google_Service_Gmail_Message(); 
    $mime = rtrim(strtr(base64_encode("THIS IS A TEST MESSAGE"), '+/', '-_'), '='); 
    $msg->setRaw($mime); 
    $service->users_messages->send("me", $msg); 
    echo "OK";   
} catch (Exception $ex) {
    echo $ex->getMessage(); 

}

编辑:我意识到我的Google_Service_Gmail范围已设为READ_ONLY。我尝试按api source on line 34将其更改为MAIL_GOOGLE_COM,但仍然出现错误。

1 个答案:

答案 0 :(得分:0)

在根据需要更新代码中的范围后,请不要忘记通过在谷歌开发者控制台上删除旧凭据后重新生成凭据来重新连接Google API。