PHP check hosted gmail account

Problem: I have google engine account for mydomain.com. I want to get emails from one of one the hosted gmail addresses.

Solution under cut

You can access google email address in 2 ways. You can either get access token to specific account@mydomain.com using oauth flow. You can find a good example in google docs But in this  case you will need to refresh token. This could be a real problem because you will need to refresh token if it’s expired. Alternatively you can use another approach using google service account. Using this approach you can access your user accounts – i.e. user under mydomain.com and therefore you can check user email.

Use this guide in order to set up service account. Add domain-wide authority to your service account and add required scopes. Then having this done you can access email using following code.

$client = new Google_Client();
$client->setApplicationName('My App');
$client->setAuthConfigFile('path/to/service_account.json');

$client->useApplicationDefaultCredentials();
// account that we want to check 
$client->setSubject('account@mydomain.com');
$client->setAccessType('offline');  
$client->setScopes([Google_Service_Gmail::GMAIL_READONLY, Google_Service_Gmail::GMAIL_MODIFY]);

$service = new Google_Service_Gmail($client);

// we want to check all unread email messages and then mark them as read
$pageToken = null;
$exit = false;
$optParams = [
    'includeSpamTrash' => true,
    'q' => 'is:unread'
];
do {
    try {
        if ($pageToken) {
            $optParams['pageToken'] = $pageToken;
        }
        $messagesResponse = $service->users_messages->listUsersMessages('me', $optParams);
        $messages = $messagesResponse->getMessages();
        $pageToken = $messagesResponse->getNextPageToken();
        if ($messages) {
            foreach ($messages as $m) {
                $messageId = $m->getId();
                
                /* @var $message Google_Service_Gmail_Message */
                $message = $service->users_messages->get('me', $messageId);

                $modifyRequest = new Google_Service_Gmail_ModifyMessageRequest();
                $modifyRequest->setRemoveLabelIds(['UNREAD']);
                $service->users_messages->modify('me', $messageId, $modifyRequest);
                
                /* @var $payload Google_Service_Gmail_MessagePart */
                $payload = $message->getPayload();

                /** @var Google_Service_Gmail_MessagePartHeader[] $headers */
                $headers = $payload->getHeaders();

                // do what ever you need  
            }
        }
    } catch (Exception $e) {
        // log an error
    }
} while ($pageToken && !$exit);

What is important here. I used “google/apiclient”: “v2.0.0-RC7” I think it’s already stable enough. And this version has a lot and lot of improvements.

If you have any questions – please comment and I will help you.

Leave a Reply

Your email address will not be published. Required fields are marked *