php - 使用 Php 的 Gmail Api 在执行时抛出“权限不足”消息
问题描述
我试图将 Gmail Api 与 PHP 一起使用。我修改了谷歌文档快速入门中给我的代码。我可以从我的 gmail 帐户中获取标签,但是当我尝试发送邮件时,它会引发错误Insufficient Permission。谁能告诉我在 PHP 中使用 Gmail API 发送邮件的正确方法?
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Gmail API PHP Quickstart');
$client->setScopes(array(
"https://www.googleapis.com/auth/plus.login",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/plus.me"
));
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
echo "\n\n Got the token path";
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
echo "\n\n token expired";
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
echo "\n\n Got the refreshed token";
} 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->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
echo "\n\n Created a new token ";
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
echo "\n\n directory not created. Directory created";
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
echo "\n\n got the access token";
}
// echo json_encode($client);
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
echo json_encode($client);
$service = new Google_Service_Gmail($client);
echo json_encode($service);
$user = 'me';
$results = $service->users_labels->listUsersLabels($user);
if (count($results->getLabels()) == 0) {
print "No labels found.\n";
} else {
print "Labels:\n";
foreach ($results->getLabels() as $label) {
printf("- %s\n", $label->getName());
}
}
function createMessage($email) {
echo "\n\n\ncreate message function called";
$message = new Google_Service_Gmail_Message();
$email = strtr(base64_encode($email), array('+' => '-', '/' => '_'));
$message->setRaw($email);
return $message;
}
function sendMessage($service, $userId, $message) {
echo "\n\n\n\n send message called\n\n\n";
try {
$message = $service->users_messages->send($userId, $message);
print 'Message with ID: ' . $message->getId() . ' sent.';
return $message;
} catch (Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
}
$email='<email_address>';
$message = createMessage(<email_address>');
sendMessage($service," <email_address>",$message);
解决方案
推荐阅读
- shiny - 单击actionButton后将css添加到元素
- google-maps - 多边形如何知道顶点是否在谷歌地图上移动
- string - 如何测试 Robot Framework 中的字符串变量是否为空?
- ios - 使 Collection 符合自定义协议
- sql - 用 NULL 值替换/评估嵌套查询 | 甲骨文 SQL
- jenkins - jenkins:发布时出现异常,异常消息[权限被拒绝]
- excel - VBA/Excel 距离计算器 (Google API)
- javascript - 从 UTC 格式获取月份的天数
- c - 复合文字和指针
- laravel - .htaccess X-Frame-Options 标头未为某些 Laravel 路由设置