Check Gmail from a scheduled job after one-time consent
See more GMail REST API Examples
First run desktop authorization with gmail.readonly and offline access. This applies to personal Gmail and Workspace accounts subject to organization policies. Configure a job to run this code using the same private working directory and user identity. Each run refreshes the token and displays up to ten inbox message headers.
Save the original OAuth client credentials in a private gmail-client.json containing client_id and client_secret. The existing gmail-token.json supplies the refresh token. Use protected credential storage in a deployed application and serialize runs sharing these files. An invalid_grant response requires reconnecting the account. External OAuth apps in Testing normally receive refresh tokens that expire after seven days when Gmail scopes are requested. Google token expiration guidance.
This is a repeatable inbox check. To process each mailbox change across runs, see mailbox synchronization.
Chilkat Objective-C Downloads
#import <CkoFileAccess.h>
#import <CkoJsonObject.h>
#import <CkoHttp.h>
#import <CkoHttpRequest.h>
#import <CkoHttpResponse.h>
#import <CkoStringTable.h>
#import <CkoStringBuilder.h>
BOOL success = NO;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
CkoFileAccess *files = [[CkoFileAccess alloc] init];
// Recover the previous complete file if a run stopped during replacement.
int fileStatus = [[files FileExists3: @"gmail-token.json"] intValue];
if (fileStatus < 0) {
NSLog(@"%@",@"Could not inspect gmail-token.json.");
return;
}
if (fileStatus == 0) {
int backupStatus = [[files FileExists3: @"gmail-token.json.previous"] intValue];
if (backupStatus < 0) {
NSLog(@"%@",@"Could not inspect the backup file.");
return;
}
if (backupStatus == 1) {
success = [files FileRename: @"gmail-token.json.previous" newPath: @"gmail-token.json"];
if (success != YES) {
NSLog(@"%@",@"Could not restore the previous complete file.");
return;
}
fileStatus = 1;
}
}
CkoJsonObject *token = [[CkoJsonObject alloc] init];
success = [token LoadFile: @"gmail-token.json"];
if (success != YES) {
NSLog(@"%@",@"Could not read gmail-token.json from the private working directory.");
return;
}
if (([[token JsonTypeOf: @"refresh_token"] intValue] != 1) || ([token StringOfEquals: @"refresh_token" value: @"" caseSensitive: YES] == YES)) {
NSLog(@"%@",@"Authorize this account for offline access first.");
return;
}
CkoJsonObject *client = [[CkoJsonObject alloc] init];
success = [client LoadFile: @"gmail-client.json"];
if (success != YES) {
NSLog(@"%@",@"Could not load the private OAuth client file.");
return;
}
if (([[client JsonTypeOf: @"client_id"] intValue] != 1) || ([[client JsonTypeOf: @"client_secret"] intValue] != 1)) {
NSLog(@"%@",@"gmail-client.json must contain client_id and client_secret.");
return;
}
CkoHttp *http = [[CkoHttp alloc] init];
http.RequireSslCertVerify = YES;
CkoHttpRequest *form = [[CkoHttpRequest alloc] init];
form.HttpVerb = @"POST";
form.ContentType = @"application/x-www-form-urlencoded";
[form AddParam: @"grant_type" value: @"refresh_token"];
[form AddParam: @"client_id" value: [client StringOf: @"client_id"]];
[form AddParam: @"client_secret" value: [client StringOf: @"client_secret"]];
[form AddParam: @"refresh_token" value: [token StringOf: @"refresh_token"]];
CkoHttpResponse *resp = [[CkoHttpResponse alloc] init];
CkoJsonObject *reply = [[CkoJsonObject alloc] init];
success = [http HttpReq: @"https://oauth2.googleapis.com/token" request: form response: resp];
if ([resp.StatusCode intValue] == 0) {
NSLog(@"%@",@"The token endpoint did not return an HTTP response.");
return;
}
if ((success != YES) || ([resp.StatusCode intValue] != 200)) {
NSLog(@"%@%d",@"Token refresh failed. HTTP ",[resp.StatusCode intValue]);
success = [reply Load: resp.BodyStr];
if (success == YES) {
if ([reply StringOfEquals: @"error" value: @"invalid_grant" caseSensitive: YES] == YES) {
NSLog(@"%@",@"Reconnect this account with interactive authorization.");
}
}
return;
}
success = [reply Load: resp.BodyStr];
if (success != YES) {
NSLog(@"%@",@"Could not parse the refresh response.");
return;
}
if (([[reply JsonTypeOf: @"access_token"] intValue] != 1) || ([reply StringOfEquals: @"access_token" value: @"" caseSensitive: YES] == YES)) {
NSLog(@"%@",@"Expected access_token in the response.");
return;
}
// Google usually omits the refresh token. Preserve it unless a replacement is returned.
if (([[reply JsonTypeOf: @"refresh_token"] intValue] != 1) || ([reply StringOfEquals: @"refresh_token" value: @"" caseSensitive: YES] == YES)) {
success = [reply UpdateString: @"refresh_token" value: [token StringOf: @"refresh_token"]];
if (success != YES) {
NSLog(@"%@",reply.LastErrorText);
return;
}
}
if (([reply HasMember: @"scope"] != YES) && ([[token JsonTypeOf: @"scope"] intValue] == 1)) {
success = [reply UpdateString: @"scope" value: [token StringOf: @"scope"]];
if (success != YES) {
NSLog(@"%@",reply.LastErrorText);
return;
}
}
// Prepare the complete replacement before moving the last committed file.
success = [reply WriteFile: @"gmail-token.json.new"];
if (success != YES) {
NSLog(@"%@",@"Could not write the replacement file.");
return;
}
if ([files FileExists: @"gmail-token.json"] == YES) {
if ([files FileExists: @"gmail-token.json.previous"] == YES) {
success = [files FileDelete: @"gmail-token.json.previous"];
if (success != YES) {
NSLog(@"%@",@"Could not rotate the previous backup.");
return;
}
}
success = [files FileRename: @"gmail-token.json" newPath: @"gmail-token.json.previous"];
if (success != YES) {
NSLog(@"%@",@"Could not retain the previous complete file.");
return;
}
}
success = [files FileRename: @"gmail-token.json.new" newPath: @"gmail-token.json"];
if (success != YES) {
NSLog(@"%@",@"Could not commit the replacement. The previous complete file is retained.");
return;
}
http.AuthToken = [reply StringOf: @"access_token"];
success = [http HttpNoBody: @"GET" url: @"https://gmail.googleapis.com/gmail/v1/users/me/messages?labelIds=INBOX&maxResults=10" response: resp];
if ([resp.StatusCode intValue] == 0) {
NSLog(@"%@",@"Gmail did not return an HTTP response.");
return;
}
if ((success != YES) || ([resp.StatusCode intValue] < 200) || ([resp.StatusCode intValue] >= 300)) {
NSLog(@"%@%d",@"Gmail HTTP ",[resp.StatusCode intValue]);
success = [reply Load: resp.BodyStr];
if (success == YES) {
NSLog(@"%@",[reply StringOf: @"error.message"]);
}
return;
}
success = [reply Load: resp.BodyStr];
if (success != YES) {
NSLog(@"%@",@"Expected a Gmail JSON response.");
return;
}
CkoStringTable *ids = [[CkoStringTable alloc] init];
int i = 0;
while ((i < [[reply SizeOfArray: @"messages"] intValue])) {
reply.I = [NSNumber numberWithInt: i];
success = [ids Append: [reply StringOf: @"messages[i].id"]];
if (success != YES) {
NSLog(@"%@",ids.LastErrorText);
return;
}
i = i + 1;
}
CkoStringBuilder *url = [[CkoStringBuilder alloc] init];
i = 0;
while ((i < [ids.Count intValue])) {
[url SetString: @"https://gmail.googleapis.com/gmail/v1/users/me/messages/"];
[url Append: [http UrlEncode: [ids StringAt: [NSNumber numberWithInt: i]]]];
[url Append: @"?format=metadata&metadataHeaders=From&metadataHeaders=Subject"];
success = [http HttpNoBody: @"GET" url: [url GetAsString] response: resp];
if ([resp.StatusCode intValue] == 0) {
NSLog(@"%@",@"Gmail did not return an HTTP response.");
return;
}
if ((success != YES) || ([resp.StatusCode intValue] < 200) || ([resp.StatusCode intValue] >= 300)) {
NSLog(@"%@%d",@"Gmail HTTP ",[resp.StatusCode intValue]);
success = [reply Load: resp.BodyStr];
if (success == YES) {
NSLog(@"%@",[reply StringOf: @"error.message"]);
}
return;
}
success = [reply Load: resp.BodyStr];
if (success != YES) {
NSLog(@"%@",@"Expected a Gmail JSON response.");
return;
}
NSLog(@"%@%@",@"Message: ",[ids StringAt: [NSNumber numberWithInt: i]]);
int h = 0;
while ((h < [[reply SizeOfArray: @"payload.headers"] intValue])) {
reply.I = [NSNumber numberWithInt: h];
NSLog(@"%@%@%@",[reply StringOf: @"payload.headers[i].name"],@": ",[reply StringOf: @"payload.headers[i].value"]);
h = h + 1;
}
i = i + 1;
}
NSLog(@"%@%d",@"Inbox messages checked: ",[ids.Count intValue]);