Sample code for 30+ languages & platforms
PowerBuilder

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 PowerBuilder Downloads

PowerBuilder
integer li_rc
integer li_Success
oleobject loo_Imap
integer li_NumMessages
integer li_StartSeqnum
oleobject loo_Bundle
integer n

li_Success = 0

//  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.

loo_Imap = create oleobject
li_rc = loo_Imap.ConnectToNewObject("Chilkat.Imap")
if li_rc < 0 then
    destroy loo_Imap
    MessageBox("Error","Connecting to COM object failed")
    return
end if

loo_Imap.Ssl = 1
loo_Imap.Port = 993

li_Success = loo_Imap.Connect("imap.example.com")
if li_Success = 0 then
    Write-Debug loo_Imap.LastErrorText
    destroy loo_Imap
    return
end if

li_Success = loo_Imap.Login("user@example.com","myPassword")
if li_Success = 0 then
    Write-Debug loo_Imap.LastErrorText
    destroy loo_Imap
    return
end if

//  SelectMailbox returns the number of messages in the mailbox, or -1 on failure.
li_NumMessages = loo_Imap.SelectMailbox("Inbox")
if li_NumMessages < 0 then
    Write-Debug loo_Imap.LastErrorText
    destroy loo_Imap
    return
end if

//  Download the 10 most recent messages (headers only).
li_StartSeqnum = li_NumMessages - 9
if li_StartSeqnum < 1 then
    li_StartSeqnum = 1
end if

loo_Bundle = create oleobject
li_rc = loo_Bundle.ConnectToNewObject("Chilkat.EmailBundle")

li_Success = loo_Imap.FetchRange(1,li_StartSeqnum,10,loo_Bundle)
if li_Success = 0 then
    Write-Debug loo_Imap.LastErrorText
    destroy loo_Imap
    destroy loo_Bundle
    return
end if

n = loo_Bundle.MessageCount
Write-Debug "Fetched " + string(n) + " message headers."

li_Success = loo_Imap.Disconnect()
if li_Success = 0 then
    Write-Debug loo_Imap.LastErrorText
    destroy loo_Imap
    destroy loo_Bundle
    return
end if



destroy loo_Imap
destroy loo_Bundle