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

Fetch Oldest/Newest IMAP Email

Emails may be downloaded by sequence number. Assuming the selected mailbox is not empty, the oldest email is at sequence number 1, and the newest email is at sequence number N. The FetchSingle method may be used to download by sequence number.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- This example assumes 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("mail.testemail.net")
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")
if not success then
    print(imap.last_error_text)
    return
end

-- After selecting a mailbox, the NumMessages property
-- contains the number of emails in the selected mailbox.
local n = imap.num_messages

if n > 0 then
    -- The oldest email is always at sequence number 1.
    local isUid = false

    local oldestEmail = chilkat.Email.new()
    success = imap:fetch_email(false, 1, isUid, oldestEmail)
    if not success then
        print(imap.last_error_text)
        return
    end

    -- Display the From and Subject
    print(oldestEmail.from_address)
    print(oldestEmail.subject)

    print("--")

    -- The newest email is at sequence number N:
    local newestEmail = chilkat.Email.new()
    success = imap:fetch_email(false, n, isUid, newestEmail)
    if not success then
        print(imap.last_error_text)
        return
    end

    -- Display the From and Subject
    print(newestEmail.from_address)
    print(newestEmail.subject)
end

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