Users.threads:Gmail API中的列表与maxResults不兼容

时间:2015-11-06 23:38:52

标签: php multithreading google-oauth google-api-php-client gmail-api

出于某种原因,Gmail API中的MaxResult无法正常工作,查询结果为我提供了邮箱中的完整线程列表。

这是代码,有人看到问题吗?

<?php
require_once '/path/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setAuthConfigFile('client_secret.json');
$client->addScope(Google_Service_Gmail::GMAIL_MODIFY,GMAIL_READONLY);

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {

  $client->setAccessToken($_SESSION['access_token']);
  $drive_service = new Google_Service_Gmail($client);

  $threads = array();
  $pageToken = NULL;
  $maxResults = 10;
  do {
    try {
      $opt_param = array();
      $opt_param['maxResults'] = $maxResults;
      if ($pageToken) {
        $opt_param['pageToken'] = $pageToken;
      }
      $threadsResponse = $drive_service->users_threads->listUsersThreads("mail@gmail.com", $opt_param);
      if ($threadsResponse->getThreads()) {
        $threads = array_merge($threads, $threadsResponse->getThreads());
        $pageToken = $threadsResponse->getNextPageToken();
      }
    } catch (Exception $e) {
      print 'An error occurred: ' . $e->getMessage();
      $pageToken = NULL;
    }
  } while ($pageToken);

  foreach ($threads as $thread) {
    print 'Thread with ID: ' . $thread->getId() . '<br/>';
  }

} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/path/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

2 个答案:

答案 0 :(得分:2)

它确实有效,但您的代码会循环,直到响应中没有nextPageToken为止。如果您只想要第一批10条消息,请忽略循环:

$threads = array();
$maxResults = 10;

$opt_param = array();
$opt_param['maxResults'] = $maxResults;
$threadsResponse = $drive_service->users_threads->listUsersThreads("mail@gmail.com", $opt_param);

if ($threadsResponse->getThreads()) {
  $threads = array_merge($threads, $threadsResponse->getThreads());
}

foreach ($threads as $thread) {
  print 'Thread with ID: ' . $thread->getId() . '<br/>';
}

答案 1 :(得分:0)

如果所需的maxResults少于API每页返回的结果数(我认为当前设置为100),则只需删除循环即可。

如果您要对结果数量设置一个最大限制,该数量限制大于每页返回的数量(例如,最大1k),以使脚本不会运行成千上万的电子邮件(例如,20k),那么以下内容可能对您有用。

 } while ($pageToken);

 } while ($pageToken && ($threads < $maxResults));