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 Delphi DLL Downloads
var
success: Boolean;
files: HCkFileAccess;
fileStatus: Integer;
backupStatus: Integer;
token: HCkJsonObject;
client: HCkJsonObject;
http: HCkHttp;
form: HCkHttpRequest;
resp: HCkHttpResponse;
reply: HCkJsonObject;
ids: HCkStringTable;
i: Integer;
url: HCkStringBuilder;
h: Integer;
begin
success := False;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
files := CkFileAccess_Create();
// Recover the previous complete file if a run stopped during replacement.
fileStatus := CkFileAccess_FileExists3(files,'gmail-token.json');
if (fileStatus < 0) then
begin
Memo1.Lines.Add('Could not inspect gmail-token.json.');
Exit;
end;
if (fileStatus = 0) then
begin
backupStatus := CkFileAccess_FileExists3(files,'gmail-token.json.previous');
if (backupStatus < 0) then
begin
Memo1.Lines.Add('Could not inspect the backup file.');
Exit;
end;
if (backupStatus = 1) then
begin
success := CkFileAccess_FileRename(files,'gmail-token.json.previous','gmail-token.json');
if (success <> True) then
begin
Memo1.Lines.Add('Could not restore the previous complete file.');
Exit;
end;
fileStatus := 1;
end;
end;
token := CkJsonObject_Create();
success := CkJsonObject_LoadFile(token,'gmail-token.json');
if (success <> True) then
begin
Memo1.Lines.Add('Could not read gmail-token.json from the private working directory.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(token,'refresh_token') <> 1) or (CkJsonObject_StringOfEquals(token,'refresh_token','',True) = True)) then
begin
Memo1.Lines.Add('Authorize this account for offline access first.');
Exit;
end;
client := CkJsonObject_Create();
success := CkJsonObject_LoadFile(client,'gmail-client.json');
if (success <> True) then
begin
Memo1.Lines.Add('Could not load the private OAuth client file.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(client,'client_id') <> 1) or (CkJsonObject_JsonTypeOf(client,'client_secret') <> 1)) then
begin
Memo1.Lines.Add('gmail-client.json must contain client_id and client_secret.');
Exit;
end;
http := CkHttp_Create();
CkHttp_putRequireSslCertVerify(http,True);
form := CkHttpRequest_Create();
CkHttpRequest_putHttpVerb(form,'POST');
CkHttpRequest_putContentType(form,'application/x-www-form-urlencoded');
CkHttpRequest_AddParam(form,'grant_type','refresh_token');
CkHttpRequest_AddParam(form,'client_id',CkJsonObject__stringOf(client,'client_id'));
CkHttpRequest_AddParam(form,'client_secret',CkJsonObject__stringOf(client,'client_secret'));
CkHttpRequest_AddParam(form,'refresh_token',CkJsonObject__stringOf(token,'refresh_token'));
resp := CkHttpResponse_Create();
reply := CkJsonObject_Create();
success := CkHttp_HttpReq(http,'https://oauth2.googleapis.com/token',form,resp);
if (CkHttpResponse_getStatusCode(resp) = 0) then
begin
Memo1.Lines.Add('The token endpoint did not return an HTTP response.');
Exit;
end;
if ((success <> True) or (CkHttpResponse_getStatusCode(resp) <> 200)) then
begin
Memo1.Lines.Add('Token refresh failed. HTTP ' + IntToStr(CkHttpResponse_getStatusCode(resp)));
success := CkJsonObject_Load(reply,CkHttpResponse__bodyStr(resp));
if (success = True) then
begin
if (CkJsonObject_StringOfEquals(reply,'error','invalid_grant',True) = True) then
begin
Memo1.Lines.Add('Reconnect this account with interactive authorization.');
end;
end;
Exit;
end;
success := CkJsonObject_Load(reply,CkHttpResponse__bodyStr(resp));
if (success <> True) then
begin
Memo1.Lines.Add('Could not parse the refresh response.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(reply,'access_token') <> 1) or (CkJsonObject_StringOfEquals(reply,'access_token','',True) = True)) then
begin
Memo1.Lines.Add('Expected access_token in the response.');
Exit;
end;
// Google usually omits the refresh token. Preserve it unless a replacement is returned.
if ((CkJsonObject_JsonTypeOf(reply,'refresh_token') <> 1) or (CkJsonObject_StringOfEquals(reply,'refresh_token','',True) = True)) then
begin
success := CkJsonObject_UpdateString(reply,'refresh_token',CkJsonObject__stringOf(token,'refresh_token'));
if (success <> True) then
begin
Memo1.Lines.Add(CkJsonObject__lastErrorText(reply));
Exit;
end;
end;
if ((CkJsonObject_HasMember(reply,'scope') <> True) and (CkJsonObject_JsonTypeOf(token,'scope') = 1)) then
begin
success := CkJsonObject_UpdateString(reply,'scope',CkJsonObject__stringOf(token,'scope'));
if (success <> True) then
begin
Memo1.Lines.Add(CkJsonObject__lastErrorText(reply));
Exit;
end;
end;
// Prepare the complete replacement before moving the last committed file.
success := CkJsonObject_WriteFile(reply,'gmail-token.json.new');
if (success <> True) then
begin
Memo1.Lines.Add('Could not write the replacement file.');
Exit;
end;
if (CkFileAccess_FileExists(files,'gmail-token.json') = True) then
begin
if (CkFileAccess_FileExists(files,'gmail-token.json.previous') = True) then
begin
success := CkFileAccess_FileDelete(files,'gmail-token.json.previous');
if (success <> True) then
begin
Memo1.Lines.Add('Could not rotate the previous backup.');
Exit;
end;
end;
success := CkFileAccess_FileRename(files,'gmail-token.json','gmail-token.json.previous');
if (success <> True) then
begin
Memo1.Lines.Add('Could not retain the previous complete file.');
Exit;
end;
end;
success := CkFileAccess_FileRename(files,'gmail-token.json.new','gmail-token.json');
if (success <> True) then
begin
Memo1.Lines.Add('Could not commit the replacement. The previous complete file is retained.');
Exit;
end;
CkHttp_putAuthToken(http,CkJsonObject__stringOf(reply,'access_token'));
success := CkHttp_HttpNoBody(http,'GET','https://gmail.googleapis.com/gmail/v1/users/me/messages?labelIds=INBOX&maxResults=10',resp);
if (CkHttpResponse_getStatusCode(resp) = 0) then
begin
Memo1.Lines.Add('Gmail did not return an HTTP response.');
Exit;
end;
if ((success <> True) or (CkHttpResponse_getStatusCode(resp) < 200) or (CkHttpResponse_getStatusCode(resp) >= 300)) then
begin
Memo1.Lines.Add('Gmail HTTP ' + IntToStr(CkHttpResponse_getStatusCode(resp)));
success := CkJsonObject_Load(reply,CkHttpResponse__bodyStr(resp));
if (success = True) then
begin
Memo1.Lines.Add(CkJsonObject__stringOf(reply,'error.message'));
end;
Exit;
end;
success := CkJsonObject_Load(reply,CkHttpResponse__bodyStr(resp));
if (success <> True) then
begin
Memo1.Lines.Add('Expected a Gmail JSON response.');
Exit;
end;
ids := CkStringTable_Create();
i := 0;
while (i < CkJsonObject_SizeOfArray(reply,'messages')) do
begin
CkJsonObject_putI(reply,i);
success := CkStringTable_Append(ids,CkJsonObject__stringOf(reply,'messages[i].id'));
if (success <> True) then
begin
Memo1.Lines.Add(CkStringTable__lastErrorText(ids));
Exit;
end;
i := i + 1;
end;
url := CkStringBuilder_Create();
i := 0;
while (i < CkStringTable_getCount(ids)) do
begin
CkStringBuilder_SetString(url,'https://gmail.googleapis.com/gmail/v1/users/me/messages/');
CkStringBuilder_Append(url,CkHttp__urlEncode(http,CkStringTable__stringAt(ids,i)));
CkStringBuilder_Append(url,'?format=metadata&metadataHeaders=From&metadataHeaders=Subject');
success := CkHttp_HttpNoBody(http,'GET',CkStringBuilder__getAsString(url),resp);
if (CkHttpResponse_getStatusCode(resp) = 0) then
begin
Memo1.Lines.Add('Gmail did not return an HTTP response.');
Exit;
end;
if ((success <> True) or (CkHttpResponse_getStatusCode(resp) < 200) or (CkHttpResponse_getStatusCode(resp) >= 300)) then
begin
Memo1.Lines.Add('Gmail HTTP ' + IntToStr(CkHttpResponse_getStatusCode(resp)));
success := CkJsonObject_Load(reply,CkHttpResponse__bodyStr(resp));
if (success = True) then
begin
Memo1.Lines.Add(CkJsonObject__stringOf(reply,'error.message'));
end;
Exit;
end;
success := CkJsonObject_Load(reply,CkHttpResponse__bodyStr(resp));
if (success <> True) then
begin
Memo1.Lines.Add('Expected a Gmail JSON response.');
Exit;
end;
Memo1.Lines.Add('Message: ' + CkStringTable__stringAt(ids,i));
h := 0;
while (h < CkJsonObject_SizeOfArray(reply,'payload.headers')) do
begin
CkJsonObject_putI(reply,h);
Memo1.Lines.Add(CkJsonObject__stringOf(reply,'payload.headers[i].name') + ': ' + CkJsonObject__stringOf(reply,'payload.headers[i].value'));
h := h + 1;
end;
i := i + 1;
end;
Memo1.Lines.Add('Inbox messages checked: ' + IntToStr(CkStringTable_getCount(ids)));
CkFileAccess_Dispose(files);
CkJsonObject_Dispose(token);
CkJsonObject_Dispose(client);
CkHttp_Dispose(http);
CkHttpRequest_Dispose(form);
CkHttpResponse_Dispose(resp);
CkJsonObject_Dispose(reply);
CkStringTable_Dispose(ids);
CkStringBuilder_Dispose(url);