(403)权限不足,无法通过gmail API发送电子邮件 - php

我可以检索带有身份验证的电子邮件来阅读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('[email protected]', '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,但仍然收到错误。

参考方案

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

希望它对您有用。

PHP:不推荐使用password_hash的'salt'选项 - php

我正在使用密码哈希进行注册。我需要手动创建Salt,以下是我使用的代码:$options = [ 'cost' => 11, 'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM) ]; $password = password_hash( $this->…

PHP-全局变量的性能和内存问题 - php

假设情况:我在php中运行一个复杂的站点,并且我使用了很多全局变量。我可以将变量存储在现有的全局范围内,例如$_REQUEST['userInfo'],$_REQUEST['foo']和$_REQUEST['bar']等,然后将许多不同的内容放入请求范围内(这将是适当的用法,因为这些数据指的是要求自…

PHP strtotime困境 - php

有人可以解释为什么这在我的服务器上输出为true吗?date_default_timezone_set('Europe/Bucharest'); var_dump( strtotime('29.03.2015 03:00', time()) === strtotime('29.03.2015 04:00�…

php-casperjs获取内部文本 - php

我正在为casperjs使用php包装器-https://github.com/alwex/php-casperjs我正在网上自动化一些重复的工作,我需要访问一个项目的innerText,但是我尚不清楚如何从casperjs浏览器访问dom。我认为在js中我会var arr = document.querySelector('label.input…

PHP Laravel从另一个驱动器读取文件 - php

我目前正在学习Laravel。我想知道是否有一种方法可以在Laravel中使用Storage::从另一个硬盘访问文件(使用Windows)。例如,我在驱动器C:上安装了带有Laravel的Xampp,但是我想访问网站目录之外的E:上的文件。我试过使用Storage::files('E:')和File::files('E:…