2015-07-21 126 views
1

我能够检索带有认证的电子邮件以阅读google api。我遵循quick start guid,并且能够在设置客户端并将其链接到client_secret.json文件后阅读电子邮件。(403)权限不足,用于在gmail api上发送电子邮件

什么到目前为止,我的工作是这样的:

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

令我百思不解的是,当我尝试以下方法来尝试发送邮件,每次谷歌的指示,我得到的错误:

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。我试图改变这个MAIL_GOOGLE_COMapi source on line 34,但仍然有错误。

+0

所以我想这只是另一个失败的原因,在现代软件开发的雾蒙蒙的迷雾中。 – 1N5818

+0

您链接到的快速入门指南适用于Google云端硬盘。请尝试遵循[Gmail快速入门指南](https://developers.google.com/gmail/api/quickstart/php)。 – abraham

回答

3

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

我希望它能为你工作。

0

不要忘记再删除谷歌开发者控制台上的旧后生成的凭证通过谷歌API重新连接,按照需要在代码更新范围之后。