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;
}