Sample code for 30+ languages & platforms
AutoIt

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

AutoIt
Local $bSuccess = False

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

$oImap = ObjCreate("Chilkat.Imap")

; Connect to an IMAP server.
; Use TLS
$oImap.Ssl = True
$oImap.Port = 993
$bSuccess = $oImap.Connect("mail.testemail.net")
If ($bSuccess = False) Then
    ConsoleWrite($oImap.LastErrorText & @CRLF)
    Exit
EndIf

; Login
$bSuccess = $oImap.Login("***","***")
If ($bSuccess = False) Then
    ConsoleWrite($oImap.LastErrorText & @CRLF)
    Exit
EndIf

; Select an IMAP mailbox
$bSuccess = $oImap.SelectMailbox("Inbox")
If ($bSuccess = False) Then
    ConsoleWrite($oImap.LastErrorText & @CRLF)
    Exit
EndIf

; After selecting a mailbox, the NumMessages property
; contains the number of emails in the selected mailbox.
Local $iN
$iN = $oImap.NumMessages

If ($iN > 0) Then

    ; The oldest email is always at sequence number 1.
Local $bIsUid = False

    $oOldestEmail = ObjCreate("Chilkat.Email")
    $bSuccess = $oImap.FetchEmail(False,1,$bIsUid,$oOldestEmail)
    If ($bSuccess = False) Then
        ConsoleWrite($oImap.LastErrorText & @CRLF)
        Exit
    EndIf

    ; Display the From and Subject
    ConsoleWrite($oOldestEmail.FromAddress & @CRLF)
    ConsoleWrite($oOldestEmail.Subject & @CRLF)

    ConsoleWrite("--" & @CRLF)

    ; The newest email is at sequence number N:
    $oNewestEmail = ObjCreate("Chilkat.Email")
    $bSuccess = $oImap.FetchEmail(False,$iN,$bIsUid,$oNewestEmail)
    If ($bSuccess = False) Then
        ConsoleWrite($oImap.LastErrorText & @CRLF)
        Exit
    EndIf

    ; Display the From and Subject
    ConsoleWrite($oNewestEmail.FromAddress & @CRLF)
    ConsoleWrite($oNewestEmail.Subject & @CRLF)

EndIf

; Disconnect from the IMAP server.
$bSuccess = $oImap.Disconnect()