我能够检索电子邮件与身份验证阅读谷歌api。我遵循了快速入门指南,并且能够在设置客户端并将其链接到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%sn", $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 %sn", $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;
令我困惑的是,当我尝试以下尝试发送邮件时,根据谷歌的说明,我得到了错误:
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%sn", $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 %sn", $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
。我尝试根据第34行api源将其更改为MAIL_GOOGLE_COM
,但仍然得到了错误。
将范围更改为:GMAIL_COMPOSE而不是MAIL_GOOGLE_COM,然后尝试通过Google API重新连接,以便再次获得权限。还可以在scope数组中添加多个作用域。
我希望它对你有用。
不要忘记通过Google API重新连接,在Google开发者控制台上删除旧的凭据后,根据需要更新代码中的作用域。