0

I simply want to access my own gmail account and retrieve the 10 newest messages. I'm having a very hard time authenticating so that I can even attempt this.

I followed the instructions here: https://developers.google.com/gmail/api/quickstart/php

All appears to work, but now what? The documentation is tough to follow. The API calls work using API Explorer but how should I access the oAuth token in PHP?

Google provides the following exaple function:

function listMessages($service, $userId) {
  $pageToken = NULL;
  $messages = array();
  $opt_param = array();
  do {
    try {
      if ($pageToken) {
        $opt_param['pageToken'] = $pageToken;
      }
      $messagesResponse = $service->users_messages->listUsersMessages($userId, $opt_param);
      if ($messagesResponse->getMessages()) {
        $messages = array_merge($messages, $messagesResponse->getMessages());
        $pageToken = $messagesResponse->getNextPageToken();
      }
    } catch (Exception $e) {
      print 'An error occurred: ' . $e->getMessage();
    }
  } while ($pageToken);

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

  return $messages;
}

How do I get the $service? I assume that refers to the keys stored in client_secrets.json but I'm unsure how to access.

I know this is a somewhat basic question (so basic that Google doesn't explain it) but I'm sure I'm not the only one to struggle with this.

Thanks!

user2029890
  • 2,493
  • 6
  • 34
  • 65

1 Answers1

0

You're in a common catch-22 - we've all been there.

You want to use Google API xxx (gmail in your case), so you read the docs about the the Gmail API. They make a passing reference to OAuth, along with a link, but there is a fire-hose of information there, so you skim read it and then go back to the Gmail docs hoping for a bit of sample code to copy/paste.

Unfortunately, you're probably going to have to go back to the OAuth docs and invest a few hours reading the. You'll know when you've understood it because you will be able to explain to yourself the difference between Authentication and Authorization. The main difficulty is that most of the sample code and explanations relate to the use case where your application has many users, each wishing to securely access their own email using your app. The use case where a single user wants to access his own email is an edge case and thus not well explained. this post might help How do I authorise an app (web or installed) without user intervention? (canonical ?). I wrote it for GDrive, but it will probably work for Gmail also.

pinoyyid
  • 21,499
  • 14
  • 64
  • 115