Sample code for 30+ languages & platforms
Lua

Send HTML Email with Attachments

See more SMTP Examples

Demonstrates how to send an HTML email with file attachments.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

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

local mailman = chilkat.MailMan.new()

mailman.smtp_host = "smtp.my-starttls-mail-server.com"

mailman.smtp_username = "MY-SMTP-USERNAME"
mailman.smtp_password = "MY-SMTP-PASSWORD"

mailman.start_tls = true
mailman.smtp_port = 587

-- Create a new email object
local email = chilkat.Email.new()
email.subject = "Test SMTP API to Send HTML Email with Attachments"
email.from = "Joe Programmer <joe@my-starttls-mail-server.com>"
email:add_to("Chilkat Support", "support@chilkatsoft.com")

-- Add a plain-text alternative body, which will likely never be seen.
-- (It is shown if the receiving email client is incapable of displaying HTML email.)
email:add_plain_text_alternative_body("This is a plain-text alternative body...")

-- Our HTML will include an image, so add the related image here.
local contentIdStarfish = email:add_related_file("qa_data/jpg/starfish.jpg")
if not email.last_method_success then
    print(email.last_error_text)
    return
end

-- The src attribute for the image tag is set to the contentIdStarfish:
local sbHtml = chilkat.StringBuilder.new()
sbHtml:append("<html><body><p>This is an HTML email with an embedded image.</p>")
sbHtml:append("<p><img src=\"cid:CONTENT_ID_STARFISH\" /></p></body></html>")
local numReplacements = sbHtml:replace("CONTENT_ID_STARFISH", contentIdStarfish)

email:add_html_alternative_body(sbHtml:get_as_string())

-- Finally, add some attachments to the email.
-- Add a file attachment.
local success = email:add_file_attachment2("qa_data/pdf/fishing.pdf", "application/pdf")
if not success then
    print(email.last_error_text)
    return
end

-- Add an attachment where the content is contained in a string.
local content = "This is the content of the 2nd attached file."
email:add_string_attachment("someText.txt", content)

-- Send the HTML email.
success = mailman:send_email(email)
if not success then
    print(mailman.last_error_text)
    return
end

success = mailman:close_smtp_connection()
if not success then
    print("Connection to SMTP server not closed cleanly.")
end

print("HTML email with attachments sent!")