Sample code for 30+ languages & platforms
PowerBuilder

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

PowerBuilder
integer li_rc
integer li_Success
oleobject loo_Imap
integer n
integer li_IsUid
oleobject loo_OldestEmail
oleobject loo_NewestEmail

li_Success = 0

// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

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

// Connect to an IMAP server.
// Use TLS
loo_Imap.Ssl = 1
loo_Imap.Port = 993
li_Success = loo_Imap.Connect("mail.testemail.net")
if li_Success = 0 then
    Write-Debug loo_Imap.LastErrorText
    destroy loo_Imap
    return
end if

// Login
li_Success = loo_Imap.Login("***","***")
if li_Success = 0 then
    Write-Debug loo_Imap.LastErrorText
    destroy loo_Imap
    return
end if

// Select an IMAP mailbox
li_Success = loo_Imap.SelectMailbox("Inbox")
if li_Success = 0 then
    Write-Debug loo_Imap.LastErrorText
    destroy loo_Imap
    return
end if

// After selecting a mailbox, the NumMessages property
// contains the number of emails in the selected mailbox.

n = loo_Imap.NumMessages

if n > 0 then

    // The oldest email is always at sequence number 1.
    li_IsUid = 0

    loo_OldestEmail = create oleobject
    li_rc = loo_OldestEmail.ConnectToNewObject("Chilkat.Email")

    li_Success = loo_Imap.FetchEmail(0,1,li_IsUid,loo_OldestEmail)
    if li_Success = 0 then
        Write-Debug loo_Imap.LastErrorText
        destroy loo_Imap
        destroy loo_OldestEmail
        return
    end if

    // Display the From and Subject
    Write-Debug loo_OldestEmail.FromAddress
    Write-Debug loo_OldestEmail.Subject

    Write-Debug "--"

    // The newest email is at sequence number N:
    loo_NewestEmail = create oleobject
    li_rc = loo_NewestEmail.ConnectToNewObject("Chilkat.Email")

    li_Success = loo_Imap.FetchEmail(0,n,li_IsUid,loo_NewestEmail)
    if li_Success = 0 then
        Write-Debug loo_Imap.LastErrorText
        destroy loo_Imap
        destroy loo_OldestEmail
        destroy loo_NewestEmail
        return
    end if

    // Display the From and Subject
    Write-Debug loo_NewestEmail.FromAddress
    Write-Debug loo_NewestEmail.Subject

end if

// Disconnect from the IMAP server.
li_Success = loo_Imap.Disconnect()


destroy loo_Imap
destroy loo_OldestEmail
destroy loo_NewestEmail