0
votes

I'm trying to search a user's gmail account for emails with attachments and collect statistics. I can successfully use oauth to authenticate and then use the gmail api to get the message ids ($id). Then I need to get headers, and finally, I need to get the messages themselves.

That has proven difficult. (And I eventually need to do this for all messages from all folders.)

I have occasionally gotten the headers using the gmail api, but everything bogged down and the code below crashes my server (WTF?).

I am considering using Zend to get the headers and attachments because it supports oauth, but the getmessage($id) function of Zend does not use the id that the api gives needs and I haven't found how to convert them.

Any help would be immensely appreciated.

<?php
/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
include_once "templates/base.php";
session_start();

set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Gmail.php';


/************************************************
  ATTENTION: Fill in these values! Make sure
  the redirect URI is to this page, e.g:
  http://localhost:8080/user-example.php
 ************************************************/
$client_id = 'XXXXXXXXXXX.apps.googleusercontent.com'; // Client ID
$client_secret = 'YYYYYYYYYYYYY';  // Client Secret
$redirect_uri = 'https://www.example.com/Google/testgmail.php'; // Redirect URI

/************************************************
  Make an API request on behalf of a user. In
  this case we need to have a valid OAuth 2.0
  token for the user, so we need to send them
  through a login flow. To do this we need some
  information from our API console project.
 ************************************************/
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/gmail.readonly");

$gm_service = new Google_Service_Gmail($client);



/************************************************
  Boilerplate auth management - see
  user-example.php for details.
 ************************************************/
if (isset($_REQUEST['logout'])) {
  unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
} else {
  $authUrl = $client->createAuthUrl();
}

/************************************************
  If we're signed in, retrieve channels from YouTube
  and a list of files from Drive.
 ************************************************/
if ($client->getAccessToken()) {
  $_SESSION['access_token'] = $client->getAccessToken();
 }

echo pageHeader("User Query - Multiple APIs");


function listMessages($service, $userId) {
  $pageToken = NULL;
  $messages = array();
  $opt_param = array();
  do {
    try {
      if ($pageToken) {
        $opt_param['pageToken'] = $pageToken;
        $opt_param['q'] = 'filename:(jpg OR png OR gif)';
        $opt_param['maxResults'] = 100;
      }
      $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);

  $optParamsGet = array();  
  $optParamsGet['format'] = 'metadata';
  foreach ($messages as $message) {
      $message_id = $message->getId();
      print 'Message with ID: ' . $message_id . '<br/>';

// This is the section that causes it to crash !!!          
//      $message2 = $service->users_messages->get($userId,$message_id,$optParamsGet); //if this line is uncommented, then everything stops working.
//          if ($message2->getPayload()) {
//              $messagePayload = $message2->getPayload();
//              $headers = $message2->getPayload()->getHeaders();
//              var_dump($headers);
//          }
// This is the section that causes it to crash !!!   

  }   
  return $messages;
}

?>
<div class="box">
  <div class="request">
    <?php if (isset($authUrl)) { ?>
      <a class='login' href='<?php echo $authUrl; ?>'>Connect Me!</a>
    <?php } else {

      echo "<h3>Results Of Gmail search:</h3>";
      $messagelist =  listMessages($gm_service, 'me');

    } ?>
  </div>
</div>
1

1 Answers

0
votes

$id is the index of the message inside of the inbox. So the most recent email received has the index 0

You can find an implementation of the algorith for search email with attachments in this repo https://bitbucket.org/startupbootstrap/email-attachments/src/ae4739bf956c8958a4128a34eb04c8fd855c0500/EmailAttachments.php?at=master#cl-85