Lua Requires Chilkat v11.0.0+
Lua
Scan for Emails with Attachments and Save Attachments to Files
Scan for emails with attachments and save attachments.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.
local imap = chilkat.Imap.new()
-- Connect to an IMAP server.
-- Use TLS
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
-- We can choose to fetch UIDs or sequence numbers.
local fetchUids = true
-- Get the message IDs of all the emails in the mailbox
local messageSet = chilkat.MessageSet.new()
success = imap:query_mbx("ALL", fetchUids, messageSet)
if not success then
print(imap.last_error_text)
return
end
-- Fetch the email headers into a bundle object:
local bundle = chilkat.EmailBundle.new()
local headersOnly = true
success = imap:fetch_msg_set(headersOnly, messageSet, bundle)
if not success then
print(imap.last_error_text)
return
end
-- Scan for emails with attachments, and save the attachments
-- to a sub-directory.
local fullEmail = chilkat.Email.new()
local emailHeader = chilkat.Email.new()
local i = 0
while i < bundle.message_count do
-- The bundle contains email headers..
bundle:email_at(i, emailHeader)
-- Does this email have attachments?
-- Use GetMailNumAttach because the attachments
-- are not actually in the email object because
-- we only downloaded headers.
local numAttach = imap:get_mail_num_attach(emailHeader)
if numAttach > 0 then
-- Download the entire email and save the
-- attachments. (Remember, we
-- need to download the entire email because
-- only the headers were previously downloaded.
-- The ckx-imap-uid header field is added when
-- headers are downloaded. This makes it possible
-- to get the UID from the email object.
local uidStr = emailHeader:get_header_field("ckx-imap-uid")
local uid = tonumber(uidStr)
success = imap:fetch_email(false, uid, true, fullEmail)
if not success then
print(imap.last_error_text)
return
end
success = fullEmail:save_all_attachments("attachmentsDir")
for j = 0, numAttach - 1 do
local filename = imap:get_mail_attach_filename(emailHeader, j)
print(filename)
end
end
i = i + 1
end
-- Disconnect from the IMAP server.
success = imap:disconnect()