Sample code for 30+ languages & platforms
JavaScript Requires Chilkat v11.0.0+

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.

Google documentation

Note
This example is intended for running within a Chilkat.Js embedded JavaScript engine. All Chilkat JavaScript examples require Chilkat v11.4.0 or greater.
JavaScript
var success = false;

//  Assumes Chilkat is unlocked. See Global Unlock Sample.

var files = new CkFileAccess();
//  Recover the previous complete file if a run stopped during replacement.
var fileStatus = files.FileExists3("gmail-token.json");
if (fileStatus < 0) {
    console.log("Could not inspect gmail-token.json.");
    return;
}

if (fileStatus == 0) {
    var backupStatus = files.FileExists3("gmail-token.json.previous");
    if (backupStatus < 0) {
        console.log("Could not inspect the backup file.");
        return;
    }

    if (backupStatus == 1) {
        success = files.FileRename("gmail-token.json.previous","gmail-token.json");
        if (success !== true) {
            console.log("Could not restore the previous complete file.");
            return;
        }

        fileStatus = 1;
    }

}

var token = new CkJsonObject();
success = token.LoadFile("gmail-token.json");
if (success !== true) {
    console.log("Could not read gmail-token.json from the private working directory.");
    return;
}

if ((token.JsonTypeOf("refresh_token") !== 1) || (token.StringOfEquals("refresh_token","",true) == true)) {
    console.log("Authorize this account for offline access first.");
    return;
}

var client = new CkJsonObject();
success = client.LoadFile("gmail-client.json");
if (success !== true) {
    console.log("Could not load the private OAuth client file.");
    return;
}

if ((client.JsonTypeOf("client_id") !== 1) || (client.JsonTypeOf("client_secret") !== 1)) {
    console.log("gmail-client.json must contain client_id and client_secret.");
    return;
}

var http = new CkHttp();
http.RequireSslCertVerify = true;
var form = new CkHttpRequest();
form.HttpVerb = "POST";
form.ContentType = "application/x-www-form-urlencoded";
form.AddParam("grant_type","refresh_token");
form.AddParam("client_id",client.StringOf("client_id"));
form.AddParam("client_secret",client.StringOf("client_secret"));
form.AddParam("refresh_token",token.StringOf("refresh_token"));
var resp = new CkHttpResponse();
var reply = new CkJsonObject();
success = http.HttpReq("https://oauth2.googleapis.com/token",form,resp);
if (resp.StatusCode == 0) {
    console.log("The token endpoint did not return an HTTP response.");
    return;
}

if ((success !== true) || (resp.StatusCode !== 200)) {
    console.log("Token refresh failed. HTTP " + resp.StatusCode);
    success = reply.Load(resp.BodyStr);
    if (success == true) {
        if (reply.StringOfEquals("error","invalid_grant",true) == true) {
            console.log("Reconnect this account with interactive authorization.");
        }

    }

    return;
}

success = reply.Load(resp.BodyStr);
if (success !== true) {
    console.log("Could not parse the refresh response.");
    return;
}

if ((reply.JsonTypeOf("access_token") !== 1) || (reply.StringOfEquals("access_token","",true) == true)) {
    console.log("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") !== 1) || (reply.StringOfEquals("refresh_token","",true) == true)) {
    success = reply.UpdateString("refresh_token",token.StringOf("refresh_token"));
    if (success !== true) {
        console.log(reply.LastErrorText);
        return;
    }

}

if ((reply.HasMember("scope") !== true) && (token.JsonTypeOf("scope") == 1)) {
    success = reply.UpdateString("scope",token.StringOf("scope"));
    if (success !== true) {
        console.log(reply.LastErrorText);
        return;
    }

}

//  Prepare the complete replacement before moving the last committed file.
success = reply.WriteFile("gmail-token.json.new");
if (success !== true) {
    console.log("Could not write the replacement file.");
    return;
}

if (files.FileExists("gmail-token.json") == true) {
    if (files.FileExists("gmail-token.json.previous") == true) {
        success = files.FileDelete("gmail-token.json.previous");
        if (success !== true) {
            console.log("Could not rotate the previous backup.");
            return;
        }

    }

    success = files.FileRename("gmail-token.json","gmail-token.json.previous");
    if (success !== true) {
        console.log("Could not retain the previous complete file.");
        return;
    }

}

success = files.FileRename("gmail-token.json.new","gmail-token.json");
if (success !== true) {
    console.log("Could not commit the replacement. The previous complete file is retained.");
    return;
}

http.AuthToken = reply.StringOf("access_token");
success = http.HttpNoBody("GET","https://gmail.googleapis.com/gmail/v1/users/me/messages?labelIds=INBOX&maxResults=10",resp);
if (resp.StatusCode == 0) {
    console.log("Gmail did not return an HTTP response.");
    return;
}

if ((success !== true) || (resp.StatusCode < 200) || (resp.StatusCode >= 300)) {
    console.log("Gmail HTTP " + resp.StatusCode);
    success = reply.Load(resp.BodyStr);
    if (success == true) {
        console.log(reply.StringOf("error.message"));
    }

    return;
}

success = reply.Load(resp.BodyStr);
if (success !== true) {
    console.log("Expected a Gmail JSON response.");
    return;
}

var ids = new CkStringTable();
var i = 0;
while ((i < reply.SizeOfArray("messages"))) {
    reply.I = i;
    success = ids.Append(reply.StringOf("messages[i].id"));
    if (success !== true) {
        console.log(ids.LastErrorText);
        return;
    }

    i = i+1;
}

var url = new CkStringBuilder();
i = 0;
while ((i < ids.Count)) {
    url.SetString("https://gmail.googleapis.com/gmail/v1/users/me/messages/");
    url.Append(http.UrlEncode(ids.StringAt(i)));
    url.Append("?format=metadata&metadataHeaders=From&metadataHeaders=Subject");
    success = http.HttpNoBody("GET",url.GetAsString(),resp);
    if (resp.StatusCode == 0) {
        console.log("Gmail did not return an HTTP response.");
        return;
    }

    if ((success !== true) || (resp.StatusCode < 200) || (resp.StatusCode >= 300)) {
        console.log("Gmail HTTP " + resp.StatusCode);
        success = reply.Load(resp.BodyStr);
        if (success == true) {
            console.log(reply.StringOf("error.message"));
        }

        return;
    }

    success = reply.Load(resp.BodyStr);
    if (success !== true) {
        console.log("Expected a Gmail JSON response.");
        return;
    }

    console.log("Message: " + ids.StringAt(i));
    var h = 0;
    while ((h < reply.SizeOfArray("payload.headers"))) {
        reply.I = h;
        console.log(reply.StringOf("payload.headers[i].name") + ": " + reply.StringOf("payload.headers[i].value"));
        h = h+1;
    }

    i = i+1;
}

console.log("Inbox messages checked: " + ids.Count);