Morby-Raybould Morby-Raybould - 1 year ago 138
PHP Question

GMail API - How to display full emails from inbox

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

ini_set('display_errors' , 'On');

// Start Session

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

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


// Check if there is an auth token
$_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
} else
$loginUrl = $client->createAuthUrl();
echo 'Click <a href="' . $loginUrl . '">here</a> to login';

// Check if we have an access token ready for API Call
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';

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download