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

VBScript
Dim fso, outFile
Set fso = CreateObject("Scripting.FileSystemObject")
'Create a Unicode (utf-16) output text file.
Set outFile = fso.CreateTextFile("output.txt", True, True)

success = 0

'  Assumes Chilkat is unlocked. See Global Unlock Sample.

set files = CreateObject("Chilkat.FileAccess")
'  Recover the previous complete file if a run stopped during replacement.
fileStatus = files.FileExists3("gmail-token.json")
If (fileStatus < 0) Then
    outFile.WriteLine("Could not inspect gmail-token.json.")
    WScript.Quit
End If

If (fileStatus = 0) Then
    backupStatus = files.FileExists3("gmail-token.json.previous")
    If (backupStatus < 0) Then
        outFile.WriteLine("Could not inspect the backup file.")
        WScript.Quit
    End If

    If (backupStatus = 1) Then
        success = files.FileRename("gmail-token.json.previous","gmail-token.json")
        If (success <> 1) Then
            outFile.WriteLine("Could not restore the previous complete file.")
            WScript.Quit
        End If

        fileStatus = 1
    End If

End If

set token = CreateObject("Chilkat.JsonObject")
success = token.LoadFile("gmail-token.json")
If (success <> 1) Then
    outFile.WriteLine("Could not read gmail-token.json from the private working directory.")
    WScript.Quit
End If

If ((token.JsonTypeOf("refresh_token") <> 1) Or (token.StringOfEquals("refresh_token","",1) = 1)) Then
    outFile.WriteLine("Authorize this account for offline access first.")
    WScript.Quit
End If

set client = CreateObject("Chilkat.JsonObject")
success = client.LoadFile("gmail-client.json")
If (success <> 1) Then
    outFile.WriteLine("Could not load the private OAuth client file.")
    WScript.Quit
End If

If ((client.JsonTypeOf("client_id") <> 1) Or (client.JsonTypeOf("client_secret") <> 1)) Then
    outFile.WriteLine("gmail-client.json must contain client_id and client_secret.")
    WScript.Quit
End If

set http = CreateObject("Chilkat.Http")
http.RequireSslCertVerify = 1
set form = CreateObject("Chilkat.HttpRequest")
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")
set resp = CreateObject("Chilkat.HttpResponse")
set reply = CreateObject("Chilkat.JsonObject")
success = http.HttpReq("https://oauth2.googleapis.com/token",form,resp)
If (resp.StatusCode = 0) Then
    outFile.WriteLine("The token endpoint did not return an HTTP response.")
    WScript.Quit
End If

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

    End If

    WScript.Quit
End If

success = reply.Load(resp.BodyStr)
If (success <> 1) Then
    outFile.WriteLine("Could not parse the refresh response.")
    WScript.Quit
End If

If ((reply.JsonTypeOf("access_token") <> 1) Or (reply.StringOfEquals("access_token","",1) = 1)) Then
    outFile.WriteLine("Expected access_token in the response.")
    WScript.Quit
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","",1) = 1)) Then
    success = reply.UpdateString("refresh_token",token.StringOf("refresh_token"))
    If (success <> 1) Then
        outFile.WriteLine(reply.LastErrorText)
        WScript.Quit
    End If

End If

If ((reply.HasMember("scope") <> 1) And (token.JsonTypeOf("scope") = 1)) Then
    success = reply.UpdateString("scope",token.StringOf("scope"))
    If (success <> 1) Then
        outFile.WriteLine(reply.LastErrorText)
        WScript.Quit
    End If

End If

'  Prepare the complete replacement before moving the last committed file.
success = reply.WriteFile("gmail-token.json.new")
If (success <> 1) Then
    outFile.WriteLine("Could not write the replacement file.")
    WScript.Quit
End If

If (files.FileExists("gmail-token.json") = 1) Then
    If (files.FileExists("gmail-token.json.previous") = 1) Then
        success = files.FileDelete("gmail-token.json.previous")
        If (success <> 1) Then
            outFile.WriteLine("Could not rotate the previous backup.")
            WScript.Quit
        End If

    End If

    success = files.FileRename("gmail-token.json","gmail-token.json.previous")
    If (success <> 1) Then
        outFile.WriteLine("Could not retain the previous complete file.")
        WScript.Quit
    End If

End If

success = files.FileRename("gmail-token.json.new","gmail-token.json")
If (success <> 1) Then
    outFile.WriteLine("Could not commit the replacement. The previous complete file is retained.")
    WScript.Quit
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
    outFile.WriteLine("Gmail did not return an HTTP response.")
    WScript.Quit
End If

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

    WScript.Quit
End If

success = reply.Load(resp.BodyStr)
If (success <> 1) Then
    outFile.WriteLine("Expected a Gmail JSON response.")
    WScript.Quit
End If

set ids = CreateObject("Chilkat.StringTable")
i = 0
Do While (i < reply.SizeOfArray("messages"))
    reply.I = i
    success = ids.Append(reply.StringOf("messages[i].id"))
    If (success <> 1) Then
        outFile.WriteLine(ids.LastErrorText)
        WScript.Quit
    End If

    i = i + 1
Loop
set url = CreateObject("Chilkat.StringBuilder")
i = 0
Do While (i < ids.Count)
    success = url.SetString("https://gmail.googleapis.com/gmail/v1/users/me/messages/")
    success = url.Append(http.UrlEncode(ids.StringAt(i)))
    success = url.Append("?format=metadata&metadataHeaders=From&metadataHeaders=Subject")
    success = http.HttpNoBody("GET",url.GetAsString(),resp)
    If (resp.StatusCode = 0) Then
        outFile.WriteLine("Gmail did not return an HTTP response.")
        WScript.Quit
    End If

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

        WScript.Quit
    End If

    success = reply.Load(resp.BodyStr)
    If (success <> 1) Then
        outFile.WriteLine("Expected a Gmail JSON response.")
        WScript.Quit
    End If

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

outFile.Close