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

Search Gmail by sender, subject, date, or attachment

See more GMail REST API Examples

Choose a Gmail search query, follow every result page, and fetch From and Subject headers for each match. Edit the query to use operators such as from:, subject:, after:, before:, has:attachment, and filename:. Quoted phrases and special characters are URL-encoded once.

Gmail search dates use midnight Pacific Standard Time. Use Unix timestamps in seconds for exact date boundaries in another timezone. Spam and Trash are excluded unless includeSpamTrash=true is added. Search requires gmail.readonly or a broader mail scope. Query searches are unavailable with gmail.metadata.

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 Lua Downloads

Lua
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()
local searchQuery = "from:sender@example.com has:attachment filename:pdf"
local baseUrl = chilkat.StringBuilder.new()
baseUrl:append("https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=100&q=")
baseUrl:append(http:url_encode(searchQuery))
local url = chilkat.StringBuilder.new()
local pageToken = ""
local page = chilkat.JsonObject.new()
local total = 0
local more = true
while more do
    url:set_string(baseUrl:get_as_string())
    url:append("&pageToken=")
    url:append(http:url_encode(pageToken))
    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

    -- Keep this page while individual message requests reuse reply.
    success = reply:make_copy(page)
    if not success then
        print(reply.last_error_text)
        return
    end

    local i = 0
    while i < page:size_of_array("messages") do
        page.i = i
        local messageId = page:string_of("messages[i].id")
        url:set_string("https://gmail.googleapis.com/gmail/v1/users/me/messages/")
        url:append(http:url_encode(messageId))
        url:append("?format=metadata&metadataHeaders=From&metadataHeaders=Subject")
        success = http:http_no_body("GET", url:get_as_string(), resp)
        -- A message can disappear between the search and the metadata request.
        if resp.status_code ~= 404 then
            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

            print("Message: " .. messageId)
            local h = 0
            while h < reply:size_of_array("payload.headers") do
                reply.i = h
                print(reply:string_of("payload.headers[i].name") .. ": " .. reply:string_of("payload.headers[i].value"))
                h = h + 1
            end

            total = total + 1
        end

        i = i + 1
    end

    pageToken = ""
    if page:json_type_of("nextPageToken") == 1 then
        pageToken = page:string_of("nextPageToken")
    end

    more = pageToken ~= ""
end

print("Matching messages read: " .. total)