使用Zend获取api搜索识别的gmail消息

时间:2014-10-18 21:20:25

标签: php api zend-framework2 gmail

我正在尝试在用户的Gmail帐户中搜索带附件的电子邮件并收集统计信息。我可以成功使用oauth进行身份验证,然后使用gmail api获取消息ID($ id)。然后我需要获取标题,最后,我需要自己获取消息。

事实证明这很困难。 (我最终需要为所有文件夹中的所有邮件执行此操作。)

我偶尔会使用gmail api获取标题,但是一切都陷入困境,下面的代码崩溃了我的服务器(WTF?)。

我正在考虑使用Zend来获取头文件和附件,因为它支持oauth,但Zend的getmessage($ id)函数不使用api提供的id,我还没有找到如何转换它们。

非常感谢任何帮助。

<?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 个答案:

答案 0 :(得分:0)

$id是收件箱内信息的索引。因此,收到的最新电子邮件的索引为0

您可以在此仓库中找到包含附件的搜索电子邮件算法的实现 https://bitbucket.org/startupbootstrap/email-attachments/src/ae4739bf956c8958a4128a34eb04c8fd855c0500/EmailAttachments.php?at=master#cl-85