4

EDIT: fixed first error! Listing message ids now , still trying to work out how to display full emails from inbox, if anyone could help would appreciate it.

So I'm trying to use the GMail API to call the emails in my inbox so i can use them in my own app. I have got all the access sorted and currently have a array being returned. The problem i encounter is trying to display the messages.

My php looks as follows

<?php
ini_set('display_errors' , 'On');
error_reporting(E_ALL);

// Start Session 
session_start();

//Include API autoloader
require_once __DIR__ . '/vendor/autoload.php';

// Create Google Client
$client = new Google_Client();
$client->setClientId('ID in here');
$client->setClientSecret('Secret here');
$client->setRedirectUri('http://localhost:8888/gmail/');
$client->addScope('https://mail.google.com/');

//Create Google Service
$service = new Google_Service_Gmail($client);

if(isset($_REQUEST['logout'])){
    unset($_SESSION['access_token']);
}

// Check if there is an auth token 
if(isset($_GET['code']))
{
    $client->authenticate($_GET['code']);
    $_SESSION['access_token'] = $client->getAccessToken();
    $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($url, FILTER_VALIDATE_URL));
}

// Check for access token in session 
if(isset($_SESSION['access_token']))
{
    $client->setAccessToken($_SESSION['access_token']);
} else 
{
    $loginUrl = $client->createAuthUrl();
    echo 'Click <a href="' . $loginUrl . '">here</a> to login';
}

// Check if we have an access token ready for API Call
try
{
    if(isset($_SESSION['access_token']) && $client->getAccessToken())
    {
        //make API calls
        $messages = $service->users_messages->listUsersMessages('me',['maxResults'=> 2, 'labelIds'=> 'INBOX']);

        foreach ($messages as $message) 
        {
            print 'Message with ID: ' . $message->getId() . '<br/>';
        }

        return $messages;
    }
}
catch (Google_Auth_Exception $e)
{
    echo 'Looks like you dont have an access token or its expired';
}
adjuremods
  • 2,938
  • 2
  • 12
  • 17
  • You have to list messages as you've done, but the you have to make a separate request to [**get**](https://developers.google.com/gmail/api/v1/reference/users/messages/get#try-it) the message content as well. [**This answer**](http://stackoverflow.com/questions/32655874/cannot-get-the-body-of-email-with-gmail-php-api/32660892#32660892) might help. – Tholle Oct 04 '16 at 10:07

1 Answers1

0

Adding to what @Tholle suggested, the list of messages will have headers that has the From attribute to indicate the sender of the message. You'll just have to add a new loop inside the foreach messages or specifically call the payload[x].header.From

adjuremods
  • 2,938
  • 2
  • 12
  • 17