Sample code for 30+ languages & platforms
Lianja

Fetch a Range of IMAP Messages by Sequence Number

See more IMAP Examples

Demonstrates the Chilkat Imap.FetchRange method, which downloads a contiguous run of messages by sequence number. The arguments are headersOnly, the starting sequence number, the count of messages, and the EmailBundle that receives them. This example uses the message count returned by SelectMailbox to fetch the headers of the 10 most recent messages.

Background: IMAP sequence numbers are 1-based positions within the selected mailbox, from 1 (oldest) to the message count (newest), and they shift whenever messages are expunged. That makes FetchRange ideal for "give me the newest N" style paging within a single session, but note that sequence numbers are not stable identifiers across sessions the way UIDs are — use a UID-based approach if you need to remember which messages you have already seen.

Chilkat Lianja Downloads

Lianja
llSuccess = .F.

//  Demonstrates the Imap.FetchRange method, which downloads a contiguous run of messages by
//  sequence number.  The 1st argument is headersOnly, the 2nd is the starting sequence number,
//  the 3rd is the count of messages, and the 4th is the EmailBundle that receives them.

loImap = createobject("CkImap")

loImap.Ssl = .T.
loImap.Port = 993

llSuccess = loImap.Connect("imap.example.com")
if (llSuccess = .F.) then
    ? loImap.LastErrorText
    release loImap
    return
endif

llSuccess = loImap.Login("user@example.com","myPassword")
if (llSuccess = .F.) then
    ? loImap.LastErrorText
    release loImap
    return
endif

//  SelectMailbox returns the number of messages in the mailbox, or -1 on failure.
lnNumMessages = loImap.SelectMailbox("Inbox")
if (lnNumMessages < 0) then
    ? loImap.LastErrorText
    release loImap
    return
endif

//  Download the 10 most recent messages (headers only).
lnStartSeqnum = lnNumMessages - 9
if (lnStartSeqnum < 1) then
    lnStartSeqnum = 1
endif

loBundle = createobject("CkEmailBundle")
llSuccess = loImap.FetchRange(.T.,lnStartSeqnum,10,loBundle)
if (llSuccess = .F.) then
    ? loImap.LastErrorText
    release loImap
    release loBundle
    return
endif

n = loBundle.MessageCount
? "Fetched " + str(n) + " message headers."

llSuccess = loImap.Disconnect()
if (llSuccess = .F.) then
    ? loImap.LastErrorText
    release loImap
    release loBundle
    return
endif



release loImap
release loBundle