Php (403)权限不足,无法在gmail api上发送电子邮件

Php (403)权限不足,无法在gmail api上发送电子邮件,php,google-api,gmail,send,http-status-code-403,Php,Google Api,Gmail,Send,Http Status Code 403,我能够检索一封带有身份验证的电子邮件,用于阅读谷歌api。在设置了客户端并将其链接到client\u secret.json文件后,我可以阅读电子邮件消息 到目前为止,我所做的工作如下: <?php require 'google-api-php-client/src/Google/autoload.php'; define('APPLICATION_NAME', 'Gmail API Quickstart'); define('CREDENTIALS_PATH', '~/.creden

我能够检索一封带有身份验证的电子邮件,用于阅读谷歌api。在设置了客户端并将其链接到
client\u 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; 
我所做的只是在底部添加一个更改:

<?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(); 

}

将作用域更改为:GMAIL_COMPOSE,改为MAIL_GOOGLE_COM,然后尝试通过GOOGLE API重新连接,以便再次获得权限。您还可以在scopes数组中添加多个作用域


我希望它对你有用

不要忘记在删除Google developer console上的旧凭证后,在根据需要更新代码中的作用域后,通过Google API重新生成凭证,从而重新连接。

所以我猜这只是另一个失败的原因,现代软件开发迷雾中的奥秘。您链接到的快速入门指南是针对Google Drive的。试着按照下面的步骤来做。
<?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(); 

}