Users.threads:Gmail 中的列表 API 无法使用 maxResults

Users.threads: list in Gmail API not working with maxResults

出于某种原因,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));
}

它确实有效,但您的代码会循环直到响应中不存在 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/>';
}

如果您需要的 maxResults 小于 API 每页返回的结果数,我认为当前设置为 100,那么您可以删除循环。

如果您尝试对大于每页返回数的结果数设置最大限制(例如最大 1k),这样脚本就不会 运行 通过数千电子邮件(例如 20k),那么以下内容可能适合您。

 } while ($pageToken);

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