2014-07-01 34 views
14

我已經從Google PHP客戶端庫中下載了新的Gmail API源代碼。使用Gmail API從PHP中讀取郵件

set_include_path("./google-api-php-client-master/src/".PATH_SEPARATOR.get_include_path()); 

require_once 'Google/Client.php'; 
require_once 'Google/Service/Gmail.php'; 

$client = new Google_Client(); 
$client->setClientId($this->config->item('gmailapi_clientid')); 
$client->setClientSecret($this->config->item('gmailapi_clientsecret')); 
$client->setRedirectUri(base_url('auth')); 
$client->addScope('email'); 
//$client->addScope('profile');  
$client->addScope('https://mail.google.com');   
$client->setAccessType('offline'); 

$gmailService = new Google_Service_Gmail($client); 

我應該怎麼做未來:

我使用inititalized服務?如何使用Gmail API PHP庫閱讀Gmail郵件?

回答

2

我會從這裏開始:https://developers.google.com/gmail/api/v1/reference/users/messages/listhttps://developers.google.com/gmail/api/v1/reference/users/messages/get

需要注意的是,當你的郵件列表僅返回然後使用ID與get方法實際得到的消息內容這些消息的ID:

+1

謝謝。你知道如何獲得消息正文與PHP? $ MSG-> getPayload() - >的getParts() - > getBody();無法獲取內容 – Anandhan

+0

php庫爲gmail api完成了嗎? – Anandhan

+0

的確如此,我們只得到帶有其ID的消息列表。問題是如何使用每個ID來獲取其消息,即我試圖通過谷歌文檔,但無法找到任何線索。 –

16

出於演示的目的,你可以做這樣的事情:

 $optParams = []; 
     $optParams['maxResults'] = 5; // Return Only 5 Messages 
     $optParams['labelIds'] = 'INBOX'; // Only show messages in Inbox 
     $messages = $service->users_messages->listUsersMessages('me',$optParams); 
     $list = $messages->getMessages(); 
     $messageId = $list[0]->getId(); // Grab first Message 


     $optParamsGet = []; 
     $optParamsGet['format'] = 'full'; // Display message in payload 
     $message = $service->users_messages->get('me',$messageId,$optParamsGet); 
     $messagePayload = $message->getPayload(); 
     $headers = $message->getPayload()->getHeaders(); 
     $parts = $message->getPayload()->getParts(); 

     $body = $parts[0]['body']; 
     $rawData = $body->data; 
     $sanitizedData = strtr($rawData,'-_', '+/'); 
     $decodedMessage = base64_decode($sanitizedData); 

     var_dump($decodedMessage); 
+0

非常感謝。有可能使用listUersMessages()函數獲取消息詳細信息。因爲它非常緩慢加載第一條消息的第二十條消息 – Anandhan

+1

非常感謝,它想念我sanitizedData你能解釋爲什麼我們必須這樣做嗎? –

+1

@ Jean-LucBarat,我發現了一個比我想象的更好的解釋。信用轉到joesmo 還有額外的base64規格。但基本上你需要65個字符來編碼:26個小寫字母+26個大寫字母+10個數字= 62。 你需要兩個['+','/']和一個填充字符'='。但是它們都不是URL友好的,所以只需使用不同的字符,然後設置。上圖中的標準字符是[' - ','_'],但只要您對它們進行解碼並且不需要與其他人共享,就可以使用其他字符。 – Muffy

8

這是全功能,您可以使用它,因爲它工作得很好。

session_start(); 
     $this->load->library('google'); 
     $client = new Google_Client(); 
     $client->setApplicationName('API Project'); 
     $client->setScopes(implode(' ', array(Google_Service_Gmail::GMAIL_READONLY))); 
     //Web Applicaion (json) 
     $client->setAuthConfigFile('key/client_secret_105219sfdf2456244-bi3lasgl0qbgu5hgedg9adsdfvqmds5c0rkll.apps.googleusercontent.com.json'); 

     $client->setAccessType('offline');  

     // Redirect the URL after OAuth 
     if (isset($_GET['code'])) { 
      $client->authenticate($_GET['code']); 
      $_SESSION['access_token'] = $client->getAccessToken(); 
      $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; 
      header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); 
     } 

     // If Access Toket is not set, show the OAuth URL 
     if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { 
      $client->setAccessToken($_SESSION['access_token']); 
     } else { 
      $authUrl = $client->createAuthUrl(); 
     } 

     if ($client->getAccessToken()) { 

      $_SESSION['access_token'] = $client->getAccessToken(); 

      // Prepare the message in message/rfc822 
      try { 

       // The message needs to be encoded in Base64URL 

       $service = new Google_Service_Gmail($client); 

       $optParams = []; 
       $optParams['maxResults'] = 5; // Return Only 5 Messages 
       $optParams['labelIds'] = 'INBOX'; // Only show messages in Inbox 
       $messages = $service->users_messages->listUsersMessages('me',$optParams); 
       $list = $messages->getMessages(); 
       $messageId = $list[0]->getId(); // Grab first Message 


       $optParamsGet = []; 
       $optParamsGet['format'] = 'full'; // Display message in payload 
       $message = $service->users_messages->get('me',$messageId,$optParamsGet); 
       $messagePayload = $message->getPayload(); 
       $headers = $message->getPayload()->getHeaders(); 
       $parts = $message->getPayload()->getParts(); 

       $body = $parts[0]['body']; 
       $rawData = $body->data; 
       $sanitizedData = strtr($rawData,'-_', '+/'); 
       $decodedMessage = base64_decode($sanitizedData); 

     var_dump($decodedMessage); 

      } catch (Exception $e) { 
       print($e->getMessage()); 
       unset($_SESSION['access_token']); 
      } 

     } 

    // If there is no access token, there will show url 
    if (isset ($authUrl)) { 
      echo $authUrl; 
     } 
0

這是我用來開發電子郵件票務系統的示例代碼。它顯示瞭如何檢索標籤,消息和標題。

<?php 
require_once __DIR__ . '/vendor/autoload.php'; 


define('APPLICATION_NAME', 'Gmail API PHP Quickstart'); 
define('CREDENTIALS_PATH', '~/.credentials/gmail-php-quickstart.json'); 
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json'); 
// If modifying these scopes, delete your previously saved credentials 
// at ~/.credentials/gmail-php-quickstart.json 
define('SCOPES', implode(' ', array(
    Google_Service_Gmail::GMAIL_READONLY) 
)); 

if (php_sapi_name() != 'cli') { 
    throw new Exception('This application must be run on the command line.'); 
} 

/** 
* 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->setAuthConfig(CLIENT_SECRET_PATH); 
    $client->setAccessType('offline'); 

    // Load previously authorized credentials from a file. 
    $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH); 
    if (file_exists($credentialsPath)) { 
    $accessToken = json_decode(file_get_contents($credentialsPath), true); 
    } 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); 

    // Store the credentials to disk. 
    if(!file_exists(dirname($credentialsPath))) { 
     mkdir(dirname($credentialsPath), 0700, true); 
    } 
    file_put_contents($credentialsPath, json_encode($accessToken)); 
    printf("Credentials saved to %s\n", $credentialsPath); 
    } 
    $client->setAccessToken($accessToken); 

    // Refresh the token if it's expired. 
    if ($client->isAccessTokenExpired()) { 
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); 
    file_put_contents($credentialsPath, json_encode($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 list of Messages in user's mailbox. 
* 
* @param Google_Service_Gmail $service Authorized Gmail API instance. 
* @param string $userId User's email address. The special value 'me' 
* can be used to indicate the authenticated user. 
* @return array Array of Messages. 
*/ 
function listMessages($service, $userId, $optArr = []) { 
    $pageToken = NULL; 
    $messages = array(); 
    do { 
    try { 
     if ($pageToken) { 
     $optArr['pageToken'] = $pageToken; 
     } 
     $messagesResponse = $service->users_messages->listUsersMessages($userId, $optArr); 
     if ($messagesResponse->getMessages()) { 
     $messages = array_merge($messages, $messagesResponse->getMessages()); 
     $pageToken = $messagesResponse->getNextPageToken(); 
     } 
    } catch (Exception $e) { 
     print 'An error occurred: ' . $e->getMessage(); 
    } 
    } while ($pageToken); 

    return $messages; 
} 

function getHeaderArr($dataArr) { 
    $outArr = []; 
    foreach ($dataArr as $key => $val) { 
     $outArr[$val->name] = $val->value; 
    } 
    return $outArr; 
} 

function getBody($dataArr) { 
    $outArr = []; 
    foreach ($dataArr as $key => $val) { 
     $outArr[] = base64url_decode($val->getBody()->getData()); 
     break; // we are only interested in $dataArr[0]. Because $dataArr[1] is in HTML. 
    } 
    return $outArr; 
} 

function base64url_decode($data) { 
    return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT)); 
} 

function getMessage($service, $userId, $messageId) { 
    try { 
    $message = $service->users_messages->get($userId, $messageId); 
    print 'Message with ID: ' . $message->getId() . ' retrieved.' . "\n"; 

    return $message; 
    } catch (Exception $e) { 
    print 'An error occurred: ' . $e->getMessage(); 
    } 
} 

function listLabels($service, $userId, $optArr = []) { 
    $results = $service->users_labels->listUsersLabels($userId); 

    if (count($results->getLabels()) == 0) { 
     print "No labels found.\n"; 
    } else { 
     print "Labels:\n"; 
     foreach ($results->getLabels() as $label) { 
     printf("- %s\n", $label->getName()); 
     } 
    } 
} 

// Get the API client and construct the service object. 
$client = getClient(); 
$service = new Google_Service_Gmail($client); 
$user = 'me'; 

// Print the labels in the user's account. 
listLabels($service, $user); 

// Get the messages in the user's account. 
$messages = listMessages($service, $user, [ 
    #'maxResults' => 20, // Return 20 messages. 
    'labelIds' => 'INBOX', // Return messages in inbox. 
]); 

foreach ($messages as $message) { 
    print 'Message with ID: ' . $message->getId() . "\n"; 

    $msgObj = getMessage($service, $user, $message->getId()); 

    $headerArr = getHeaderArr($msgObj->getPayload()->getHeaders()); 

    echo 'Message-ID: ' . $headerArr['Message-ID']; 
    echo "\n"; 
    echo 'In-Reply-To: ' . (empty($headerArr['In-Reply-To']) ? '' : $headerArr['In-Reply-To']); 
    echo "\n"; 
    echo 'References: ' . (empty($headerArr['References']) ? '': $headerArr['References']); 
    echo "\n"; 

    #print_r($headerArr); 

    $bodyArr = getBody($msgObj->getPayload()->getParts()); 
    echo 'Body: ' . (empty($bodyArr[0]) ? '' : $bodyArr[0]); 
} 

參考:

https://developers.google.com/gmail/api/quickstart/php https://developers.google.com/gmail/api/v1/reference/users/messages/modify#php