Dart Requires Chilkat v11.0.0+
Dart
List Gmail message IDs across all pages
See more GMail REST API Examples
List message and thread IDs for the authenticated user. Continue with nextPageToken until it is absent. A message ID is a Gmail identifier, distinct from the RFC Message-ID header. Use it in the reading examples. Spam and Trash are excluded by default.
Authorize the application with https://www.googleapis.com/auth/gmail.readonly. The example reads the access token from gmail-token.json in a private working directory. Authorize a desktop application.
Chilkat Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
var success = false;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
final token = CkJsonObject();
success = true;
try {
token.loadFile('gmail-token.json');
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not read gmail-token.json from the private working directory.');
return;
}
if ((token.jsonTypeOf('access_token') != 1) || (token.stringOfEquals('access_token', '', true))) {
print('An OAuth access token is required.');
return;
}
final http = CkHttp();
http.requireSslCertVerify = true;
http.authToken = token.stringOf('access_token');
final resp = CkHttpResponse();
final reply = CkJsonObject();
var total = 0;
final baseUrl = CkStringBuilder();
baseUrl.append('https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=100');
final url = CkStringBuilder();
final pageToken = CkStringBuilder();
var more = true;
while (more) {
url.setString(baseUrl.getAsString());
if (pageToken.length > 0) {
url.append('&pageToken=');
url.append(http.urlEncode(pageToken.getAsString()));
}
success = true;
try {
http.httpNoBody('GET', url.getAsString(), resp);
} on ChilkatException {
success = false;
}
if (resp.statusCode == 0) {
print('Gmail did not return an HTTP response.');
return;
}
if ((!success) || ((resp.statusCode < 200) || (resp.statusCode >= 300))) {
print('Gmail HTTP ${resp.statusCode}');
success = true;
try {
reply.load(resp.bodyStr);
} on ChilkatException {
success = false;
}
if (success) {
print(reply.stringOf('error.message'));
}
return;
}
success = true;
try {
reply.load(resp.bodyStr);
} on ChilkatException {
success = false;
}
if (!success) {
print('Expected a Gmail JSON response.');
return;
}
// Gmail can omit messages when the search or mailbox is empty.
final count = reply.sizeOfArray('messages');
var i = 0;
while (i < count) {
reply.i = i;
print('${reply.stringOf('messages[i].id')} thread ${reply.stringOf('messages[i].threadId')}');
total++;
i++;
}
more = false;
if (reply.jsonTypeOf('nextPageToken') == 1) {
pageToken.setString(reply.stringOf('nextPageToken'));
more = pageToken.length > 0;
}
}
print('Messages listed: $total');
}