Lua Requires Chilkat v11.0.0+
Lua
Forward an Email using CreateForward
See more Email Object Examples
Reads an email from an IMAP server, creates a forward version of the email using the CreateForward method, and sends the email to another recipient.Chilkat Lua Downloads
local chilkat = require("chilkat")
-- This example requires the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.
-- Read the 1st (most recent) email in an Inbox.
local imap = chilkat.Imap.new()
-- Connect to an IMAP server.
imap.ssl = true
imap.port = 993
local success = imap:connect("imap.example.com")
if not success then
print(imap.last_error_text)
return
end
-- Login
success = imap:login("myLogin", "myPassword")
if not success then
print(imap.last_error_text)
return
end
-- Select an IMAP mailbox
success = imap:select_mailbox("Inbox")
if not success then
print(imap.last_error_text)
return
end
local numEmails = imap.num_messages
-- Fetch the email at the last sequence number.
-- (We are assuming the Inbox has at least 1 email)
local email = chilkat.Email.new()
success = imap:fetch_email(false, numEmails, false, email)
if not success then
print(imap.last_error_text)
return
end
-- Disconnect from the IMAP server.
imap:disconnect()
print(email.subject)
local eForward = chilkat.Email.new()
success = email:to_forward(eForward)
if not success then
print(email.last_error_text)
return
end
-- The eForward email has no To or CC recipients yet.
-- Add one or more..
eForward:add_to("Joe", "joe@example.com")
-- We also need to specify the From name/address.
eForward.from_address = "matt@someMailServer.com"
eForward.from_name = "Matt"
-- If we wish to add text at the start of the email body:
local sbHtmlBody = chilkat.StringBuilder.new()
if eForward:has_html_body() then
sbHtmlBody:append(eForward:get_html_body())
sbHtmlBody:prepend("<p>Hello, this is an email I'm forwarding to you...</p>")
eForward:set_html_body(sbHtmlBody:get_as_string())
end
local sbPtBody = chilkat.StringBuilder.new()
if eForward:has_plain_text_body() then
sbPtBody:append(eForward:get_plain_text_body())
sbPtBody:prepend("Hello, this is an email I'm forwarding to you...\r\n\r\n")
eForward:set_text_body(sbPtBody:get_as_string(), "text/plain")
end
-- We could save the .eml, then double-click on it to view in our mail program, such as Outlook or Thunderbird..
eForward:save_eml("qa_output/forward.eml")
-- We could send (forward) the email..
local mailman = chilkat.MailMan.new()
mailman.smtp_host = "smtp.example.com"
mailman.smtp_username = "myLogin"
mailman.smtp_password = "myPassword"
mailman.smtp_port = 587
mailman.start_tls = true
success = mailman:send_email(eForward)
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 Sent!")