gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 20:35:22 30 4
gpt4 key购买 nike

我能够检索带有身份验证的电子邮件以读取 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 ,但仍然出现错误。

最佳答案

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

希望对你有用。

关于php - (403) 权限不足,无法在 gmail api 上发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31546610/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com