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

Synchronize Gmail message IDs and labels between runs

See more GMail REST API Examples

Maintain gmail-sync.json containing the mailbox address, a string historyId, and a small local cache of message IDs, thread IDs, and labels. The first run scans the complete mailbox including Spam and Trash. Later runs follow all history pages and refresh only messages affected by additions, deletions, or label changes. A message GET returning 404 removes that message from the local cache.

An expired history checkpoint causes a full rebuild. The full scan records a checkpoint before listing messages, so the next run also reconciles changes made during the scan. Incremental runs save the final history response checkpoint only after every affected message has been processed. The cache and checkpoint are committed together, with a previous-file recovery path. History IDs remain strings throughout.

Run in a private directory and serialize runs sharing the cache. The sample holds the cache in memory for clarity. Larger applications can use database upserts and deletions, committing the checkpoint in the same transaction. The cache contains message identifiers and labels. Fetch MIME or selected headers when the application needs message content.

Authorize the application with https://www.googleapis.com/auth/gmail.readonly. The example reads the access token from gmail-token.json in a private working directory. Authorize a desktop application.

Google documentation

Chilkat VB.NET Downloads

VB.NET
Dim success As Boolean = False

'  Assumes Chilkat is unlocked. See Global Unlock Sample.

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("access_token") <> 1) Or (token.StringOfEquals("access_token","",True) = True)) Then
    Debug.WriteLine("An OAuth access token is required.")
    Exit Sub
End If

Dim http As New Chilkat.Http
http.RequireSslCertVerify = True
http.AuthToken = token.StringOf("access_token")
Dim resp As New Chilkat.HttpResponse
Dim reply As New Chilkat.JsonObject
Dim files As New Chilkat.FileAccess
'  Recover the previous complete file if a run stopped during replacement.
Dim fileStatus As Integer = files.FileExists3("gmail-sync.json")
If (fileStatus < 0) Then
    Debug.WriteLine("Could not inspect gmail-sync.json.")
    Exit Sub
End If

If (fileStatus = 0) Then
    Dim backupStatus As Integer = files.FileExists3("gmail-sync.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-sync.json.previous","gmail-sync.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 state As New Chilkat.JsonObject
If (fileStatus = 1) Then
    success = state.LoadFile("gmail-sync.json")
    If (success <> True) Then
        Debug.WriteLine("Could not read the existing synchronization state.")
        Exit Sub
    End If

    If ((state.JsonTypeOf("historyId") <> 1) Or (state.JsonTypeOf("messages") <> 3) Or (state.JsonTypeOf("emailAddress") <> 1)) Then
        Debug.WriteLine("The synchronization state is incomplete. Restore its previous complete copy.")
        Exit Sub
    End If

End If

success = http.HttpNoBody("GET","https://gmail.googleapis.com/gmail/v1/users/me/profile",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

If ((reply.JsonTypeOf("emailAddress") <> 1) Or (reply.StringOfEquals("emailAddress","",True) = True)) Then
    Debug.WriteLine("Expected emailAddress in the response.")
    Exit Sub
End If

If ((reply.JsonTypeOf("historyId") <> 1) Or (reply.StringOfEquals("historyId","",True) = True)) Then
    Debug.WriteLine("Expected historyId in the response.")
    Exit Sub
End If

Dim mailbox As String = reply.StringOf("emailAddress")
Dim baseline As String = reply.StringOf("historyId")
If (fileStatus = 1) Then
    If (state.StringOfEquals("emailAddress",mailbox,False) <> True) Then
        Debug.WriteLine("Use a separate synchronization file for this mailbox.")
        Exit Sub
    End If

End If

Dim fullSync As Boolean = fileStatus = 0
Dim checkpoint As String = baseline
'  A hashtable collects each changed ID once, even across multiple history records.
Dim ids As New Chilkat.Hashtable
Dim baseUrl As New Chilkat.StringBuilder
Dim url As New Chilkat.StringBuilder
Dim pageToken As String = ""
Dim more As Boolean = True

If (fullSync <> True) Then
    baseUrl.SetString("https://gmail.googleapis.com/gmail/v1/users/me/history?maxResults=500&startHistoryId=")
    baseUrl.Append(http.UrlEncode(state.StringOf("historyId")))
    Dim changeTypes As New Chilkat.StringTable
    success = changeTypes.Append("messagesAdded")
    If (success <> True) Then
        Debug.WriteLine(changeTypes.LastErrorText)
        Exit Sub
    End If

    success = changeTypes.Append("messagesDeleted")
    If (success <> True) Then
        Debug.WriteLine(changeTypes.LastErrorText)
        Exit Sub
    End If

    success = changeTypes.Append("labelsAdded")
    If (success <> True) Then
        Debug.WriteLine(changeTypes.LastErrorText)
        Exit Sub
    End If

    success = changeTypes.Append("labelsRemoved")
    If (success <> True) Then
        Debug.WriteLine(changeTypes.LastErrorText)
        Exit Sub
    End If

    Dim record As New Chilkat.JsonObject
    Dim eventPath As New Chilkat.StringBuilder
    While (more = True)
        url.SetString(baseUrl.GetAsString())
        url.Append("&pageToken=")
        url.Append(http.UrlEncode(pageToken))
        success = http.HttpNoBody("GET",url.GetAsString(),resp)
        If (resp.StatusCode = 404) Then
            Debug.WriteLine("History checkpoint expired. Rebuilding the cache.")
            fullSync = True
            more = False
        Else
            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 h As Integer = 0
            While (h < reply.SizeOfArray("history"))
                reply.I = h
                success = reply.ObjectOf2("history[i]",record)
                If (success <> True) Then
                    Debug.WriteLine(reply.LastErrorText)
                    Exit Sub
                End If

                Dim t As Integer = 0
                While (t < changeTypes.Count)
                    Dim j As Integer = 0
                    While (j < record.SizeOfArray(changeTypes.StringAt(t)))
                        eventPath.SetString(changeTypes.StringAt(t))
                        eventPath.Append("[")
                        eventPath.AppendInt(j)
                        eventPath.Append("].message.id")
                        success = ids.AddInt(record.StringOf(eventPath.GetAsString()),1)
                        If (success <> True) Then
                            Debug.WriteLine(ids.LastErrorText)
                            Exit Sub
                        End If

                        j = j + 1
                    End While
                    t = t + 1
                End While
                h = h + 1
            End While
            pageToken = ""
            If (reply.JsonTypeOf("nextPageToken") = 1) Then
                pageToken = reply.StringOf("nextPageToken")
            End If

            more = pageToken <> ""
            If (more <> True) Then
                If ((reply.JsonTypeOf("historyId") <> 1) Or (reply.StringOfEquals("historyId","",True) = True)) Then
                    Debug.WriteLine("Expected historyId in the response.")
                    Exit Sub
                End If

                checkpoint = reply.StringOf("historyId")
            End If

        End If

    End While
End If


If (fullSync = True) Then
    '  Rebuild in memory. Any failure leaves the committed file available for a retry.
    ids.Clear()
    state.Clear()
    success = state.UpdateString("emailAddress",mailbox)
    If (success <> True) Then
        Debug.WriteLine(state.LastErrorText)
        Exit Sub
    End If

    success = state.UpdateNewObject("messages")
    If (success <> True) Then
        Debug.WriteLine(state.LastErrorText)
        Exit Sub
    End If

    checkpoint = baseline
    pageToken = ""
    more = True
    While (more = True)
        url.SetString("https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=500&includeSpamTrash=true&pageToken=")
        url.Append(http.UrlEncode(pageToken))
        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

        Dim m As Integer = 0
        While (m < reply.SizeOfArray("messages"))
            reply.I = m
            success = ids.AddInt(reply.StringOf("messages[i].id"),1)
            If (success <> True) Then
                Debug.WriteLine(ids.LastErrorText)
                Exit Sub
            End If

            m = m + 1
        End While
        pageToken = ""
        If (reply.JsonTypeOf("nextPageToken") = 1) Then
            pageToken = reply.StringOf("nextPageToken")
        End If

        more = pageToken <> ""
    End While
End If


Dim messages As New Chilkat.JsonObject
success = state.ObjectOf2("messages",messages)
If (success <> True) Then
    Debug.WriteLine(state.LastErrorText)
    Exit Sub
End If

'  Message refresh order is unimportant. GetKeys appends keys to this new table.
Dim messageIds As New Chilkat.StringTable
success = ids.GetKeys(messageIds)
If (success <> True) Then
    Debug.WriteLine(ids.LastErrorText)
    Exit Sub
End If

Dim cachedMessage As New Chilkat.JsonObject
Dim i As Integer = 0
While (i < messageIds.Count)
    Dim messageId As String = messageIds.StringAt(i)
    url.SetString("https://gmail.googleapis.com/gmail/v1/users/me/messages/")
    url.Append(http.UrlEncode(messageId))
    url.Append("?format=minimal&fields=id,threadId,labelIds")
    success = http.HttpNoBody("GET",url.GetAsString(),resp)
    If (resp.StatusCode = 404) Then
        If (messages.HasMember(messageId) = True) Then
            success = messages.Delete(messageId)
            If (success <> True) Then
                Debug.WriteLine(messages.LastErrorText)
                Exit Sub
            End If

        End If

        Debug.WriteLine("Removed from cache: " & messageId)
    Else
        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

        If (reply.StringOfEquals("id",messageId,True) <> True) Then
            Debug.WriteLine("Unexpected message ID in the response.")
            Exit Sub
        End If

        success = messages.UpdateNewObject(messageId)
        If (success <> True) Then
            Debug.WriteLine(messages.LastErrorText)
            Exit Sub
        End If

        success = messages.ObjectOf2(messageId,cachedMessage)
        If (success <> True) Then
            Debug.WriteLine(messages.LastErrorText)
            Exit Sub
        End If

        success = cachedMessage.Load(reply.Emit())
        If (success <> True) Then
            Debug.WriteLine(cachedMessage.LastErrorText)
            Exit Sub
        End If

        Debug.WriteLine("Cached message: " & messageId)
    End If

    i = i + 1
End While
success = state.UpdateString("historyId",checkpoint)
If (success <> True) Then
    Debug.WriteLine(state.LastErrorText)
    Exit Sub
End If

'  Prepare the complete replacement before moving the last committed file.
success = state.WriteFile("gmail-sync.json.new")
If (success <> True) Then
    Debug.WriteLine("Could not write the replacement file.")
    Exit Sub
End If

If (files.FileExists("gmail-sync.json") = True) Then
    If (files.FileExists("gmail-sync.json.previous") = True) Then
        success = files.FileDelete("gmail-sync.json.previous")
        If (success <> True) Then
            Debug.WriteLine("Could not rotate the previous backup.")
            Exit Sub
        End If

    End If

    success = files.FileRename("gmail-sync.json","gmail-sync.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-sync.json.new","gmail-sync.json")
If (success <> True) Then
    Debug.WriteLine("Could not commit the replacement. The previous complete file is retained.")
    Exit Sub
End If

Debug.WriteLine("Synchronization committed. Cached messages: " & messages.Size)
Debug.WriteLine("Saved history ID: " & checkpoint)