2015-07-21 63 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重新連接,按照需要在代碼更新範圍之後。