简体   繁体   中英

PHP Gmail API: Trying to gather only last 100 threads

I am trying to get only last 100 threads from Gmail. I am using this function to gather threads but I don't know why It always fetches all threads and not only last 100. Also, I want to fetch them only from the inbox. Maybe there is a small mistake but I can't see what is wrong. Hope someone sees what is wrong.

function listThreads($service, $userId) {
  $threads = array();
  $pageToken = NULL;
  do {
    try {
      $opt_param = array(
    'maxResults' => 100,
    'labelIds' => 'INBOX'
  );

      if ($pageToken) {
        $opt_param['pageToken'] = $pageToken;
      }
      $threadsResponse = $service->users_threads->listUsersThreads($userId, $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/>';
  }

  return $threads;
}

I found a solution. If you set maxResults=>100 It will gather 100 threads from one token and then go ahead to gather another token to grab next 100. So the only thing I had to do was to break out once threads were fetched. Hope this helps someone. Working code:

function listThreads($service, $userId) {
  $threads = array();
  $pageToken = NULL;
  $opt_param = array(
    'maxResults' => 100,
    'labelIds' => 'INBOX'
  );

  do {
    try {


      if ($pageToken) {
        $opt_param['pageToken'] = $pageToken;
      }
      $threadsResponse = $service->users_threads->listUsersThreads($userId, $opt_param);
      if ($threadsResponse->getThreads()) {
        $threads = array_merge($threads, $threadsResponse->getThreads());

        //$pageToken = $threadsResponse->getNextPageToken();
        break;
      }
    } catch (Exception $e) {
      print 'An error occurred: ' . $e->getMessage();
      $pageToken = NULL;
      $x++;
    }
  } while ($pageToken);
  foreach ($threads as $thread) {
    print 'Thread with ID: ' . $thread->getId() . '<br/>';
  }

  return $threads;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM