Sample code for 30+ languages & platforms
Lua Requires Chilkat v10.1.2+

Send Encrypted Email using Certificate in Apple Keychain

See more Apple Keychain Examples

Send encrypted (S/MIME) email using a certificate found in the Apple Keychain.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

local email = chilkat.Email.new()
email.subject = "This email is encrypted"
email.body = "This is a S/MIME encrypted mail"
email.from = "Joe <joe@example.com>"

-- Emails are encrypted using the recipient's certificate.
local recipientEmailAddr = "jane@example2.com"
email:add_to("", recipientEmailAddr)

-- Indicate that the email is to be sent encrypted.
email.send_encrypted = true

local cert = chilkat.Cert.new()

-- The recipient's certificate is used to encrypt.
-- This will load the certificate from the Apple Keychain.
local success = cert:load_by_email_address(recipientEmailAddr)
if not success then
    print(cert.last_error_text)
    return
end

-- Specify the certificate to be used for encryption.
success = email:set_encrypt_cert(cert)
email.send_encrypted = true

local mailman = chilkat.MailMan.new()
mailman.smtp_host = "smtp.example.com"
mailman.smtp_username = "joe@example.com"
mailman.smtp_port = 587
mailman.start_tls = true

-- We'll get the SMTP password from the Apple Keychain.
-- See how we originally saved the email credentials to the Keychain here:
-- Save Email Credentials in Apple Keychain or Windows Credentials Manager
local secrets = chilkat.Secrets.new()

-- On Windows, this is the Windows Credentials Manager
-- On MacOS/iOS, it is the Apple Keychain
secrets.location = "local_manager"

-- Specify the name of the secret.
-- service and username are required.
-- appName and domain are optional.
-- Note: The values are arbitrary and can be anything you want.
local json = chilkat.JsonObject.new()
json:update_string("appName", "MyEmailApp")
json:update_string("service", "SMTP")
json:update_string("domain", "example.com")
json:update_string("username", "joe@example.com")

mailman.smtp_password = secrets:get_secret_str(json)

-- Send the encrypted email.
-- The email is encrypted and sent within the SendEmail function.
success = mailman:send_email(email)
if not success then
    print(mailman.last_error_text)
    return
end

print("Encrypted email sent!")