Sample code for 30+ languages & platforms
Lua

SendGrid HTML Email with Embedded Images

See more SendGrid Examples

Demonstrates how to send an HTML email with embedded images using SendGrid.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- This requires the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code

local req = chilkat.HttpRequest.new()
local http = chilkat.Http.new()

-- First.. load a JPG file and build an HTML img tag with the JPG data inline encoded.
-- Our HTML img tag will look like this:
-- <img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEA3ADcAA..." alt="" style="border-width:0px;" />
local bdJpg = chilkat.BinData.new()
local success = bdJpg:load_file("qa_data/jpg/starfish.jpg")
if not success then
    print("Failed to load JPG file.")
    return
end

-- Note: HTML containing embedded base64 image data may not be visible in all email clients.
-- For example, GMail might not display the image, but viewing in Outlook might be OK.
local sbHtml = chilkat.StringBuilder.new()
sbHtml:append("<html><body><b>This is a test<b><br /><img src=\"data:image/jpeg;base64,")
-- Append the base64 image data to sbHtml.
bdJpg:get_encoded_sb("base64", sbHtml)
sbHtml:append("\" alt=\"\" style=\"border-width:0px;\" /></body></html>")

local json = chilkat.JsonObject.new()
json:update_string("personalizations[0].to[0].email", "matt@chilkat.io")
json:update_string("personalizations[0].to[0].name", "Matt")
json:update_string("from.email", "admin@chilkatsoft.com")
json:update_string("subject", "Test HTML email with images")
json:update_string("content[0].type", "text/html")
json:update_sb("content[0].value", sbHtml)

http.auth_token = "SENDGRID_API_KEY"

local resp = chilkat.HttpResponse.new()
success = http:http_json("POST", "https://api.sendgrid.com/v3/mail/send", json, "application/json", resp)
if not success then
    print(http.last_error_text)
    return
end

print("response status code: " .. resp.status_code)
-- Display the response.
-- If successful, the response code is 202 and the response body string is empty.
-- (The response body string may also be empty for error response codes.)
print(resp.body_str)