Morby-Raybould Morby-Raybould - 2 months ago 34
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

<?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';
}

Answer

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