Reading messages from Gmail, in PHP, using Gmail API

Anandhan picture Anandhan · Jul 1, 2014 · Viewed 37.8k times · Source

I have donwloaded new Gmail API source code from Google PHP client library.

I inititalized the service using:

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

What should I do next? How to read Gmail messages using Gmail API PHP library?

Answer

Muffy picture Muffy · Jul 6, 2014

For the sake of demonstration, you can do something like this:

        $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);