Lua Requires Chilkat v11.0.0+
Lua
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.
Chilkat Lua Downloads
local chilkat = require("chilkat")
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local token = chilkat.JsonObject.new()
local success = token:load_file("gmail-token.json")
if not success then
print("Could not read gmail-token.json from the private working directory.")
return
end
if (token:json_type_of("access_token") ~= 1) or (token:string_of_equals("access_token", "", true)) then
print("An OAuth access token is required.")
return
end
local http = chilkat.Http.new()
http.require_ssl_cert_verify = true
http.auth_token = token:string_of("access_token")
local resp = chilkat.HttpResponse.new()
local reply = chilkat.JsonObject.new()
success = http:http_no_body("GET", "https://gmail.googleapis.com/gmail/v1/users/me/labels", resp)
if resp.status_code == 0 then
print("Gmail did not return an HTTP response.")
return
end
if (not success) or ((resp.status_code < 200) or (resp.status_code >= 300)) then
print("Gmail HTTP " .. resp.status_code)
success = reply:load(resp.body_str)
if success then
print(reply:string_of("error.message"))
end
return
end
success = reply:load(resp.body_str)
if not success then
print("Expected a Gmail JSON response.")
return
end
if reply:json_type_of("labels") ~= 4 then
print("Expected a list of labels.")
return
end
local label = chilkat.JsonObject.new()
success = reply:find_record2("labels", "name", "To review", true, label)
if not success then
print("No label with that exact name. Check the name or create the label first.")
return
end
local labelId = chilkat.StringBuilder.new()
success = label:string_of_sb("id", labelId)
if not success then
print("Could not read the label ID.")
return
end
local ids = chilkat.StringTable.new()
local baseUrl = chilkat.StringBuilder.new()
baseUrl:append("https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=500")
local searchQuery = "has:attachment"
baseUrl:append("&q=")
baseUrl:append(http:url_encode(searchQuery))
local url = chilkat.StringBuilder.new()
local pageToken = chilkat.StringBuilder.new()
local more = true
while more do
url:set_string(baseUrl:get_as_string())
if pageToken.length > 0 then
url:append("&pageToken=")
url:append(http:url_encode(pageToken:get_as_string()))
end
success = http:http_no_body("GET", url:get_as_string(), resp)
if resp.status_code == 0 then
print("Gmail did not return an HTTP response.")
return
end
if (not success) or ((resp.status_code < 200) or (resp.status_code >= 300)) then
print("Gmail HTTP " .. resp.status_code)
success = reply:load(resp.body_str)
if success then
print(reply:string_of("error.message"))
end
return
end
success = reply:load(resp.body_str)
if not success then
print("Expected a Gmail JSON response.")
return
end
-- Gmail can omit messages when the search or mailbox is empty.
local count = reply:size_of_array("messages")
local i = 0
while i < count do
reply.i = i
success = ids:append(reply:string_of("messages[i].id"))
if not success then
print("Could not retain a message ID.")
return
end
i = i + 1
end
more = false
if reply:json_type_of("nextPageToken") == 1 then
pageToken:set_string(reply:string_of("nextPageToken"))
more = pageToken.length > 0
end
end
-- Search is complete. Apply the label to each group and track confirmed progress.
local request = chilkat.JsonObject.new()
local done = 0
while done < ids.count do
request:clear()
request:update_string("addLabelIds[0]", labelId:get_as_string())
local n = 0
while (n < 1000) and ((done + n) < ids.count) do
request.i = n
request:update_string("ids[i]", ids:string_at(done + n))
n = n + 1
end
success = http:http_json("POST", "https://gmail.googleapis.com/gmail/v1/users/me/messages/batchModify", request, "application/json", resp)
if resp.status_code == 0 then
print("Gmail did not return an HTTP response.")
return
end
if (not success) or ((resp.status_code < 200) or (resp.status_code >= 300)) then
print("Gmail HTTP " .. resp.status_code)
success = reply:load(resp.body_str)
if success then
print(reply:string_of("error.message"))
end
return
end
done = done + n
print("Messages labeled so far: " .. done)
end
print("Total messages labeled: " .. done)