Sample code for 30+ languages & platforms
Lua Requires Chilkat v11.0.0+

Copy an Email from One Mailbox to Another

Copies an email from one IMAP folder to another. After running this example, copies of the email will be present in both source and destination folders.

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.

-- This example copies an email from one mailbox to another.
local imap = chilkat.Imap.new()

-- Turn on session logging:
imap.keep_session_log = true

-- 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("***", "***")
if not success then
    print(imap.last_error_text)
    return
end

-- Select an IMAP mailbox
success = imap:select_mailbox("Inbox.testing.a")
if not success then
    print(imap.last_error_text)
    return
end

local fetchUids = true

-- Get the message IDs for all emails having "Re:" in the subject.
local messageSet = chilkat.MessageSet.new()
success = imap:query_mbx("SUBJECT Re:", fetchUids, messageSet)
if not success then
    print(imap.last_error_text)
    return
end

-- Copy the messages from "Inbox.testing.a" to "Inbox.testing.b" in one call to CopyMultiple:
success = imap:copy_multiple(messageSet, "Inbox.testing.b")
if not success then
    print(imap.last_error_text)
    return
end

-- Alternatively, loop over each message in the set and
-- copy each separately:
local i = 0
while i < messageSet.count do
    local msgId = messageSet:get_id(i)
    local isUid = messageSet.has_uids

    success = imap:copy(msgId, isUid, "Inbox.testing.c")
    if not success then
        print(imap.last_error_text)
        return
    end

    i = i + 1
end

-- Display the session log.
print(imap.session_log)

-- Disconnect from the IMAP server.
success = imap:disconnect()