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

Apply a Gmail label to search results in batches

See more GMail REST API Examples

Choose a Gmail search query and an existing label name. Resolve the label ID, collect all matching message IDs before changing any labels, then submit at most 1,000 IDs per batchModify call. Empty searches send no updates. For large mailboxes, spool IDs to persistent storage. Completed batches stay applied if a later request fails; adding the same label again is safe.

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

Google documentation

Chilkat PowerBuilder Downloads

PowerBuilder
integer li_rc
long li_Success
oleobject loo_Token
oleobject loo_Http
oleobject loo_Resp
oleobject loo_Reply
oleobject loo_Label
oleobject loo_LabelId
oleobject loo_Ids
oleobject loo_BaseUrl
string ls_SearchQuery
oleobject loo_Url
oleobject loo_PageToken
long li_More
long li_Count
long i
oleobject loo_Request
long li_Done
long n

li_Success = 0

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

loo_Token = create oleobject
li_rc = loo_Token.ConnectToNewObject("Chilkat.JsonObject")
if li_rc < 0 then
    destroy loo_Token
    MessageBox("Error","Connecting to COM object failed")
    return
end if
li_Success = loo_Token.LoadFile("gmail-token.json")
if li_Success <> 1 then
    Write-Debug "Could not read gmail-token.json from the private working directory."
    destroy loo_Token
    return
end if

if (loo_Token.JsonTypeOf("access_token") <> 1) OR (loo_Token.StringOfEquals("access_token","",1) = 1) then
    Write-Debug "An OAuth access token is required."
    destroy loo_Token
    return
end if

loo_Http = create oleobject
li_rc = loo_Http.ConnectToNewObject("Chilkat.Http")

loo_Http.RequireSslCertVerify = 1
loo_Http.AuthToken = loo_Token.StringOf("access_token")
loo_Resp = create oleobject
li_rc = loo_Resp.ConnectToNewObject("Chilkat.HttpResponse")

loo_Reply = create oleobject
li_rc = loo_Reply.ConnectToNewObject("Chilkat.JsonObject")

li_Success = loo_Http.HttpNoBody("GET","https://gmail.googleapis.com/gmail/v1/users/me/labels",loo_Resp)
if loo_Resp.StatusCode = 0 then
    Write-Debug "Gmail did not return an HTTP response."
    destroy loo_Token
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Reply
    return
end if

if (li_Success <> 1) OR (loo_Resp.StatusCode < 200) OR (loo_Resp.StatusCode >= 300) then
    Write-Debug "Gmail HTTP " + string(loo_Resp.StatusCode)
    li_Success = loo_Reply.Load(loo_Resp.BodyStr)
    if li_Success = 1 then
        Write-Debug loo_Reply.StringOf("error.message")
    end if

    destroy loo_Token
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Reply
    return
end if

li_Success = loo_Reply.Load(loo_Resp.BodyStr)
if li_Success <> 1 then
    Write-Debug "Expected a Gmail JSON response."
    destroy loo_Token
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Reply
    return
end if

if loo_Reply.JsonTypeOf("labels") <> 4 then
    Write-Debug "Expected a list of labels."
    destroy loo_Token
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Reply
    return
end if

loo_Label = create oleobject
li_rc = loo_Label.ConnectToNewObject("Chilkat.JsonObject")

li_Success = loo_Reply.FindRecord2("labels","name","To review",1,loo_Label)
if li_Success <> 1 then
    Write-Debug "No label with that exact name. Check the name or create the label first."
    destroy loo_Token
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Reply
    destroy loo_Label
    return
end if

loo_LabelId = create oleobject
li_rc = loo_LabelId.ConnectToNewObject("Chilkat.StringBuilder")

li_Success = loo_Label.StringOfSb("id",loo_LabelId)
if li_Success <> 1 then
    Write-Debug "Could not read the label ID."
    destroy loo_Token
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Reply
    destroy loo_Label
    destroy loo_LabelId
    return
end if

loo_Ids = create oleobject
li_rc = loo_Ids.ConnectToNewObject("Chilkat.StringTable")

loo_BaseUrl = create oleobject
li_rc = loo_BaseUrl.ConnectToNewObject("Chilkat.StringBuilder")

loo_BaseUrl.Append("https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=500")
ls_SearchQuery = "has:attachment"
loo_BaseUrl.Append("&q=")
loo_BaseUrl.Append(loo_Http.UrlEncode(ls_SearchQuery))
loo_Url = create oleobject
li_rc = loo_Url.ConnectToNewObject("Chilkat.StringBuilder")

loo_PageToken = create oleobject
li_rc = loo_PageToken.ConnectToNewObject("Chilkat.StringBuilder")

li_More = 1
do while (li_More = 1)
    loo_Url.SetString(loo_BaseUrl.GetAsString())
    if loo_PageToken.Length > 0 then
        loo_Url.Append("&pageToken=")
        loo_Url.Append(loo_Http.UrlEncode(loo_PageToken.GetAsString()))
    end if

    li_Success = loo_Http.HttpNoBody("GET",loo_Url.GetAsString(),loo_Resp)
    if loo_Resp.StatusCode = 0 then
        Write-Debug "Gmail did not return an HTTP response."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Reply
        destroy loo_Label
        destroy loo_LabelId
        destroy loo_Ids
        destroy loo_BaseUrl
        destroy loo_Url
        destroy loo_PageToken
        return
    end if

    if (li_Success <> 1) OR (loo_Resp.StatusCode < 200) OR (loo_Resp.StatusCode >= 300) then
        Write-Debug "Gmail HTTP " + string(loo_Resp.StatusCode)
        li_Success = loo_Reply.Load(loo_Resp.BodyStr)
        if li_Success = 1 then
            Write-Debug loo_Reply.StringOf("error.message")
        end if

        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Reply
        destroy loo_Label
        destroy loo_LabelId
        destroy loo_Ids
        destroy loo_BaseUrl
        destroy loo_Url
        destroy loo_PageToken
        return
    end if

    li_Success = loo_Reply.Load(loo_Resp.BodyStr)
    if li_Success <> 1 then
        Write-Debug "Expected a Gmail JSON response."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Reply
        destroy loo_Label
        destroy loo_LabelId
        destroy loo_Ids
        destroy loo_BaseUrl
        destroy loo_Url
        destroy loo_PageToken
        return
    end if

    //  Gmail can omit messages when the search or mailbox is empty.
    li_Count = loo_Reply.SizeOfArray("messages")
    i = 0
    do while (i < li_Count)
        loo_Reply.I = i
        li_Success = loo_Ids.Append(loo_Reply.StringOf("messages[i].id"))
        if li_Success <> 1 then
            Write-Debug "Could not retain a message ID."
            destroy loo_Token
            destroy loo_Http
            destroy loo_Resp
            destroy loo_Reply
            destroy loo_Label
            destroy loo_LabelId
            destroy loo_Ids
            destroy loo_BaseUrl
            destroy loo_Url
            destroy loo_PageToken
            return
        end if

        i = i + 1
    loop
    li_More = 0
    if loo_Reply.JsonTypeOf("nextPageToken") = 1 then
        loo_PageToken.SetString(loo_Reply.StringOf("nextPageToken"))
        li_More = loo_PageToken.Length > 0
    end if

loop
//  Search is complete. Apply the label to each group and track confirmed progress.
loo_Request = create oleobject
li_rc = loo_Request.ConnectToNewObject("Chilkat.JsonObject")

li_Done = 0
do while (li_Done < loo_Ids.Count)
    loo_Request.Clear()
    loo_Request.UpdateString("addLabelIds[0]",loo_LabelId.GetAsString())
    n = 0
    do while ((n < 1000) AND ((li_Done + n) < loo_Ids.Count))
        loo_Request.I = n
        loo_Request.UpdateString("ids[i]",loo_Ids.StringAt(li_Done + n))
        n = n + 1
    loop
    li_Success = loo_Http.HttpJson("POST","https://gmail.googleapis.com/gmail/v1/users/me/messages/batchModify",loo_Request,"application/json",loo_Resp)
    if loo_Resp.StatusCode = 0 then
        Write-Debug "Gmail did not return an HTTP response."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Reply
        destroy loo_Label
        destroy loo_LabelId
        destroy loo_Ids
        destroy loo_BaseUrl
        destroy loo_Url
        destroy loo_PageToken
        destroy loo_Request
        return
    end if

    if (li_Success <> 1) OR (loo_Resp.StatusCode < 200) OR (loo_Resp.StatusCode >= 300) then
        Write-Debug "Gmail HTTP " + string(loo_Resp.StatusCode)
        li_Success = loo_Reply.Load(loo_Resp.BodyStr)
        if li_Success = 1 then
            Write-Debug loo_Reply.StringOf("error.message")
        end if

        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Reply
        destroy loo_Label
        destroy loo_LabelId
        destroy loo_Ids
        destroy loo_BaseUrl
        destroy loo_Url
        destroy loo_PageToken
        destroy loo_Request
        return
    end if

    li_Done = li_Done + n
    Write-Debug "Messages labeled so far: " + string(li_Done)
loop
Write-Debug "Total messages labeled: " + string(li_Done)


destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Reply
destroy loo_Label
destroy loo_LabelId
destroy loo_Ids
destroy loo_BaseUrl
destroy loo_Url
destroy loo_PageToken
destroy loo_Request