Sample code for 30+ languages & platforms
Lua

Send Email With Attachments

See more SMTP Examples

Demonstrates how to send an email with 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.

-- The mailman object is used for sending (SMTP) and receiving (POP3) email.
local mailman = chilkat.MailMan.new()

-- Set the SMTP server.
mailman.smtp_host = "smtp.my-tls-mail-server.com"

-- Set the SMTP login/password (if required)
mailman.smtp_username = "MY_SMTP_USERNAME"
mailman.smtp_password = "MY_SMTP_PASSWORD"

-- Connect to SMTP port 465 using TLS.
mailman.smtp_ssl = true
mailman.smtp_port = 465

-- Create a new email object
local email = chilkat.Email.new()

email.subject = "This is a test"
email.body = "This is a test"
email.from = "Chilkat Support <support@chilkatsoft.com>"
local success = email:add_to("Chilkat Admin", "admin@chilkatsoft.com")
-- To add more recipients, call AddTo, AddCC, or AddBcc once per recipient.

-- Add some attachments.
-- The AddFileAttachment method returns the value of the content-type it chose for the attachment.
local contentType = email:add_file_attachment("qa_data/jpg/starfish.jpg")
if not email.last_method_success then
    print(email.last_error_text)
    return
end

contentType = email:add_file_attachment("qa_data/pdf/fishing.pdf")
if not email.last_method_success then
    print(email.last_error_text)
    return
end

-- Call SendEmail to connect to the SMTP server and send.
-- The connection (i.e. session) to the SMTP server remains
-- open so that subsequent SendEmail calls may use the
-- same connection.
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("Mail with attachments sent!")