Lua
Lua
Download a Specific GMail Message into a Chilkat Email Object
See more GMail REST API Examples
Demonstrates how to download a GMail message into a Chilkat Email object.Chilkat Lua Downloads
local chilkat = require("chilkat")
-- This example requires the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.
local http = chilkat.Http.new()
http.auth_token = "GMAIL-ACCESS-TOKEN"
-- The id of the GMail message to download.
local id = "166e50fed0b9b0cb"
local userId = "me"
http:set_url_var("userId", "me")
http:set_url_var("id", id)
-- Fetch the email.
local url = "https://www.googleapis.com/gmail/v1/users/{$userId}/messages/{$id}?format=raw"
local sbJson = chilkat.StringBuilder.new()
local success = http:download_sb(url, "utf-8", sbJson)
if not success then
print(http.last_error_text)
return
end
local json = chilkat.JsonObject.new()
json:load_sb(sbJson)
json.emit_compact = false
if http.last_status ~= 200 then
print(json:emit())
print("Failed.")
return
end
-- The returned JSON contains something like this:
-- {
-- "id": "166e50fed0b9b0cb",
-- "threadId": "166e50fed0b9b0cb",
-- "labelIds": [
-- "CATEGORY_SOCIAL",
-- "INBOX"
-- ],
-- "snippet": "...",
-- "historyId": "582477",
-- "internalDate": "1541441317000",
-- "sizeEstimate": 28603,
-- "raw": "BASE64URL_CONTENT"
-- }
-- The RFC822 MIME of the email is contained in the "raw" as a base64URL encoded string.
-- Let's decode and load into a Chilkat email object..
local sbRaw = chilkat.StringBuilder.new()
json:string_of_sb("raw", sbRaw)
sbRaw:decode("base64url", "utf-8")
local email = chilkat.Email.new()
email:set_from_mime_sb(sbRaw)
-- Now we can use the email API to do whatever we desire..
print("From: " .. email.from_address)
print("Subject: " .. email.subject)
-- ...