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 VB.NET Downloads
Dim success As Boolean = False
' Assumes Chilkat is unlocked. See Global Unlock Sample.
Dim files As New Chilkat.FileAccess
' Recover the previous complete file if a run stopped during replacement.
Dim fileStatus As Integer = files.FileExists3("gmail-token.json")
If (fileStatus < 0) Then
Debug.WriteLine("Could not inspect gmail-token.json.")
Exit Sub
End If
If (fileStatus = 0) Then
Dim backupStatus As Integer = files.FileExists3("gmail-token.json.previous")
If (backupStatus < 0) Then
Debug.WriteLine("Could not inspect the backup file.")
Exit Sub
End If
If (backupStatus = 1) Then
success = files.FileRename("gmail-token.json.previous","gmail-token.json")
If (success <> True) Then
Debug.WriteLine("Could not restore the previous complete file.")
Exit Sub
End If
fileStatus = 1
End If
End If
Dim token As New Chilkat.JsonObject
success = token.LoadFile("gmail-token.json")
If (success <> True) Then
Debug.WriteLine("Could not read gmail-token.json from the private working directory.")
Exit Sub
End If
If ((token.JsonTypeOf("refresh_token") <> 1) Or (token.StringOfEquals("refresh_token","",True) = True)) Then
Debug.WriteLine("Authorize this account for offline access first.")
Exit Sub
End If
Dim client As New Chilkat.JsonObject
success = client.LoadFile("gmail-client.json")
If (success <> True) Then
Debug.WriteLine("Could not load the private OAuth client file.")
Exit Sub
End If
If ((client.JsonTypeOf("client_id") <> 1) Or (client.JsonTypeOf("client_secret") <> 1)) Then
Debug.WriteLine("gmail-client.json must contain client_id and client_secret.")
Exit Sub
End If
Dim http As New Chilkat.Http
http.RequireSslCertVerify = True
Dim form As New 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"))
Dim resp As New Chilkat.HttpResponse
Dim reply As New Chilkat.JsonObject
success = http.HttpReq("https://oauth2.googleapis.com/token",form,resp)
If (resp.StatusCode = 0) Then
Debug.WriteLine("The token endpoint did not return an HTTP response.")
Exit Sub
End If
If ((success <> True) Or (resp.StatusCode <> 200)) Then
Debug.WriteLine("Token refresh failed. HTTP " & resp.StatusCode)
success = reply.Load(resp.BodyStr)
If (success = True) Then
If (reply.StringOfEquals("error","invalid_grant",True) = True) Then
Debug.WriteLine("Reconnect this account with interactive authorization.")
End If
End If
Exit Sub
End If
success = reply.Load(resp.BodyStr)
If (success <> True) Then
Debug.WriteLine("Could not parse the refresh response.")
Exit Sub
End If
If ((reply.JsonTypeOf("access_token") <> 1) Or (reply.StringOfEquals("access_token","",True) = True)) Then
Debug.WriteLine("Expected access_token in the response.")
Exit Sub
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
Debug.WriteLine(reply.LastErrorText)
Exit Sub
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
Debug.WriteLine(reply.LastErrorText)
Exit Sub
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
Debug.WriteLine("Could not write the replacement file.")
Exit Sub
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
Debug.WriteLine("Could not rotate the previous backup.")
Exit Sub
End If
End If
success = files.FileRename("gmail-token.json","gmail-token.json.previous")
If (success <> True) Then
Debug.WriteLine("Could not retain the previous complete file.")
Exit Sub
End If
End If
success = files.FileRename("gmail-token.json.new","gmail-token.json")
If (success <> True) Then
Debug.WriteLine("Could not commit the replacement. The previous complete file is retained.")
Exit Sub
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
Debug.WriteLine("Gmail did not return an HTTP response.")
Exit Sub
End If
If ((success <> True) Or (resp.StatusCode < 200) Or (resp.StatusCode >= 300)) Then
Debug.WriteLine("Gmail HTTP " & resp.StatusCode)
success = reply.Load(resp.BodyStr)
If (success = True) Then
Debug.WriteLine(reply.StringOf("error.message"))
End If
Exit Sub
End If
success = reply.Load(resp.BodyStr)
If (success <> True) Then
Debug.WriteLine("Expected a Gmail JSON response.")
Exit Sub
End If
Dim ids As New Chilkat.StringTable
Dim i As Integer = 0
While (i < reply.SizeOfArray("messages"))
reply.I = i
success = ids.Append(reply.StringOf("messages[i].id"))
If (success <> True) Then
Debug.WriteLine(ids.LastErrorText)
Exit Sub
End If
i = i + 1
End While
Dim url As New Chilkat.StringBuilder
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) Then
Debug.WriteLine("Gmail did not return an HTTP response.")
Exit Sub
End If
If ((success <> True) Or (resp.StatusCode < 200) Or (resp.StatusCode >= 300)) Then
Debug.WriteLine("Gmail HTTP " & resp.StatusCode)
success = reply.Load(resp.BodyStr)
If (success = True) Then
Debug.WriteLine(reply.StringOf("error.message"))
End If
Exit Sub
End If
success = reply.Load(resp.BodyStr)
If (success <> True) Then
Debug.WriteLine("Expected a Gmail JSON response.")
Exit Sub
End If
Debug.WriteLine("Message: " & ids.StringAt(i))
Dim h As Integer = 0
While (h < reply.SizeOfArray("payload.headers"))
reply.I = h
Debug.WriteLine(reply.StringOf("payload.headers[i].name") & ": " & reply.StringOf("payload.headers[i].value"))
h = h + 1
End While
i = i + 1
End While
Debug.WriteLine("Inbox messages checked: " & ids.Count)