Search Gmail by sender, subject, date, or attachment
See more GMail REST API Examples
Choose a Gmail search query, follow every result page, and fetch From and Subject headers for each match. Edit the query to use operators such as from:, subject:, after:, before:, has:attachment, and filename:. Quoted phrases and special characters are URL-encoded once.
Gmail search dates use midnight Pacific Standard Time. Use Unix timestamps in seconds for exact date boundaries in another timezone. Spam and Trash are excluded unless includeSpamTrash=true is added. Search requires gmail.readonly or a broader mail scope. Query searches are unavailable with gmail.metadata.
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();
final searchQuery = 'from:sender@example.com has:attachment filename:pdf';
final baseUrl = CkStringBuilder();
baseUrl.append('https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=100&q=');
baseUrl.append(http.urlEncode(searchQuery));
final url = CkStringBuilder();
var pageToken = '';
final page = CkJsonObject();
var total = 0;
var more = true;
while (more) {
url.setString(baseUrl.getAsString());
url.append('&pageToken=');
url.append(http.urlEncode(pageToken));
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;
}
// Keep this page while individual message requests reuse reply.
success = true;
try {
reply.makeCopy(page);
} on ChilkatException {
success = false;
}
if (!success) {
print(reply.lastErrorText);
return;
}
var i = 0;
while (i < page.sizeOfArray('messages')) {
page.i = i;
final messageId = page.stringOf('messages[i].id');
url.setString('https://gmail.googleapis.com/gmail/v1/users/me/messages/');
url.append(http.urlEncode(messageId));
url.append('?format=metadata&metadataHeaders=From&metadataHeaders=Subject');
success = true;
try {
http.httpNoBody('GET', url.getAsString(), resp);
} on ChilkatException {
success = false;
}
// A message can disappear between the search and the metadata request.
if (resp.statusCode != 404) {
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;
}
print('Message: $messageId');
var h = 0;
while (h < reply.sizeOfArray('payload.headers')) {
reply.i = h;
print('${reply.stringOf('payload.headers[i].name')}: ${reply.stringOf('payload.headers[i].value')}');
h++;
}
total++;
}
i++;
}
pageToken = '';
if (page.jsonTypeOf('nextPageToken') == 1) {
pageToken = page.stringOf('nextPageToken');
}
more = pageToken != '';
}
print('Matching messages read: $total');
}