Sample code for 30+ languages & platforms
B4X 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

Chilkat B4X Downloads

B4X
Dim success As Boolean = False

'  Assumes Chilkat is unlocked. See Global Unlock Sample.

Dim files As ChilkatFileAccess
files.Initialize
'  Recover the previous complete file if a run stopped during replacement.
Dim fileStatus As Int = files.FileExists3("gmail-token.json")
If fileStatus < 0 Then
    Log("Could not inspect gmail-token.json.")
    Return
End If

If fileStatus = 0 Then
    Dim backupStatus As Int = files.FileExists3("gmail-token.json.previous")
    If backupStatus < 0 Then
        Log("Could not inspect the backup file.")
        Return
    End If

    If backupStatus = 1 Then
        success = files.FileRename("gmail-token.json.previous", "gmail-token.json")
        If success <> True Then
            Log("Could not restore the previous complete file.")
            Return
        End If

        fileStatus = 1
    End If

End If

Dim token As ChilkatJsonObject
token.Initialize
success = token.LoadFile("gmail-token.json")
If success <> True Then
    Log("Could not read gmail-token.json from the private working directory.")
    Return
End If

If (token.JsonTypeOf("refresh_token") <> 1) Or (token.StringOfEquals("refresh_token", "", True) = True) Then
    Log("Authorize this account for offline access first.")
    Return
End If

Dim client As ChilkatJsonObject
client.Initialize
success = client.LoadFile("gmail-client.json")
If success <> True Then
    Log("Could not load the private OAuth client file.")
    Return
End If

If (client.JsonTypeOf("client_id") <> 1) Or (client.JsonTypeOf("client_secret") <> 1) Then
    Log("gmail-client.json must contain client_id and client_secret.")
    Return
End If

Dim http As ChilkatHttp
http.Initialize("http")
http.RequireSslCertVerify = True
Dim form As ChilkatHttpRequest
form.Initialize
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"))
Dim resp As ChilkatHttpResponse
resp.Initialize
Dim reply As ChilkatJsonObject
reply.Initialize
success = http.HttpReq("https://oauth2.googleapis.com/token", form, resp)
If resp.StatusCode = 0 Then
    Log("The token endpoint did not return an HTTP response.")
    Return
End If

If (success <> True) Or (resp.StatusCode <> 200) Then
    Log("Token refresh failed. HTTP " & resp.StatusCode)
    success = reply.Load(resp.BodyStr)
    If success = True Then
        If reply.StringOfEquals("error", "invalid_grant", True) = True Then
            Log("Reconnect this account with interactive authorization.")
        End If

    End If

    Return
End If

success = reply.Load(resp.BodyStr)
If success <> True Then
    Log("Could not parse the refresh response.")
    Return
End If

If (reply.JsonTypeOf("access_token") <> 1) Or (reply.StringOfEquals("access_token", "", True) = True) Then
    Log("Expected access_token in the response.")
    Return
End If

'  Google usually omits the refresh token. Preserve it unless a replacement is returned.
If (reply.JsonTypeOf("refresh_token") <> 1) Or (reply.StringOfEquals("refresh_token", "", True) = True) Then
    success = reply.UpdateString("refresh_token", token.StringOf("refresh_token"))
    If success <> True Then
        Log(reply.LastErrorText)
        Return
    End If

End If

If (reply.HasMember("scope") <> True) And (token.JsonTypeOf("scope") = 1) Then
    success = reply.UpdateString("scope", token.StringOf("scope"))
    If success <> True Then
        Log(reply.LastErrorText)
        Return
    End If

End If

'  Prepare the complete replacement before moving the last committed file.
success = reply.WriteFile("gmail-token.json.new")
If success <> True Then
    Log("Could not write the replacement file.")
    Return
End If

If files.FileExists("gmail-token.json") = True Then
    If files.FileExists("gmail-token.json.previous") = True Then
        success = files.FileDelete("gmail-token.json.previous")
        If success <> True Then
            Log("Could not rotate the previous backup.")
            Return
        End If

    End If

    success = files.FileRename("gmail-token.json", "gmail-token.json.previous")
    If success <> True Then
        Log("Could not retain the previous complete file.")
        Return
    End If

End If

success = files.FileRename("gmail-token.json.new", "gmail-token.json")
If success <> True Then
    Log("Could not commit the replacement. The previous complete file is retained.")
    Return
End If


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 Then
    Log("Gmail did not return an HTTP response.")
    Return
End If

If (success <> True) Or (resp.StatusCode < 200) Or (resp.StatusCode >= 300) Then
    Log("Gmail HTTP " & resp.StatusCode)
    success = reply.Load(resp.BodyStr)
    If success = True Then
        Log(reply.StringOf("error.message"))
    End If

    Return
End If

success = reply.Load(resp.BodyStr)
If success <> True Then
    Log("Expected a Gmail JSON response.")
    Return
End If

Dim ids As ChilkatStringTable
ids.Initialize
Dim i As Int = 0
Do While (i < reply.SizeOfArray("messages"))
    reply.I = i
    success = ids.Append(reply.StringOf("messages[i].id"))
    If success <> True Then
        Log(ids.LastErrorText)
        Return
    End If

    i = i + 1
Loop
Dim url As ChilkatStringBuilder
url.Initialize
i = 0
Do 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 Then
        Log("Gmail did not return an HTTP response.")
        Return
    End If

    If (success <> True) Or (resp.StatusCode < 200) Or (resp.StatusCode >= 300) Then
        Log("Gmail HTTP " & resp.StatusCode)
        success = reply.Load(resp.BodyStr)
        If success = True Then
            Log(reply.StringOf("error.message"))
        End If

        Return
    End If

    success = reply.Load(resp.BodyStr)
    If success <> True Then
        Log("Expected a Gmail JSON response.")
        Return
    End If

    Log("Message: " & ids.StringAt(i))
    Dim h As Int = 0
    Do While (h < reply.SizeOfArray("payload.headers"))
        reply.I = h
        Log(reply.StringOf("payload.headers[i].name") & ": " & reply.StringOf("payload.headers[i].value"))
        h = h + 1
    Loop
    i = i + 1
Loop
Log("Inbox messages checked: " & ids.Count)