Lua Requires Chilkat v11.0.0+
Lua
Send email to blind-copy recipients with Gmail
See more GMail REST API Examples
Live send. Replace all sample addresses. Gmail takes its recipients from the submitted MIME To, Cc, and Bcc headers. Use AddBcc on a new Email and keep the Bcc header when serializing it for Gmail. Treat the submission as private because it contains the blind-copy addresses.
Authorize the application with https://www.googleapis.com/auth/gmail.send. 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()
local email = chilkat.Email.new()
-- Use the authorized mailbox or one of its configured send-as addresses.
email.from = "Sender <sender@example.com>"
success = email:add_to("Recipient", "recipient@example.net")
if not success then
print(email.last_error_text)
return
end
email.subject = "Sample message"
email.charset = "utf-8"
email.body = "Hello from the Gmail API."
-- Gmail needs the blind recipient in the submitted MIME; use the normal Chilkat 11.x Bcc behavior.
success = email:add_bcc("Blind recipient", "blind@example.org")
if not success then
print(email.last_error_text)
return
end
local mime = chilkat.BinData.new()
success = email:get_mime_bd(mime)
if not success then
print(email.last_error_text)
return
end
local request = chilkat.JsonObject.new()
success = request:update_bd("raw", "base64url", mime)
if not success then
print(request.last_error_text)
return
end
success = http:http_json("POST", "https://gmail.googleapis.com/gmail/v1/users/me/messages/send", 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
success = reply:load(resp.body_str)
if not success then
print("Expected a Gmail JSON response.")
return
end
if (reply:json_type_of("id") ~= 1) or (reply:string_of_equals("id", "", true)) then
print("Expected id in the response.")
return
end
print("Gmail message ID: " .. reply:string_of("id"))