Sample code for 30+ languages & platforms
PureBasic

Determine the Number of Unseen Email Messages

Demonstrates how to determine how many unseen messages exist in an email account on an IMAP server.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkImap.pb"
IncludeFile "CkMessageSet.pb"

Procedure ChilkatExample()

    success.i = 0

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

    imap.i = CkImap::ckCreate()
    If imap.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ; Connect to an IMAP server.
    ; Use TLS
    CkImap::setCkSsl(imap, 1)
    CkImap::setCkPort(imap, 993)
    success = CkImap::ckConnect(imap,"imap.example.com")
    If success = 0
        Debug CkImap::ckLastErrorText(imap)
        CkImap::ckDispose(imap)
        ProcedureReturn
    EndIf

    ; Login
    success = CkImap::ckLogin(imap,"***","***")
    If success = 0
        Debug CkImap::ckLastErrorText(imap)
        CkImap::ckDispose(imap)
        ProcedureReturn
    EndIf

    ; Select an IMAP mailbox
    success = CkImap::ckSelectMailbox(imap,"Inbox")
    If success = 0
        Debug CkImap::ckLastErrorText(imap)
        CkImap::ckDispose(imap)
        ProcedureReturn
    EndIf

    ; After selecting the mailbox. the total number of emails
    ; is immediately available:
    totalNum.i = CkImap::ckNumMessages(imap)
    Debug "Num messages = " + Str(totalNum)

    ; To determine the number of unseen messages, a call
    ; to Search is required, which returns the set of UIDs
    ; of all unseen messages.

    ; We can choose to fetch UIDs or sequence numbers.
    fetchUids.i = 1
    messageSet.i = CkMessageSet::ckCreate()
    If messageSet.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkImap::ckQueryMbx(imap,"UNSEEN",fetchUids,messageSet)
    If success = 0
        Debug CkImap::ckLastErrorText(imap)
        CkImap::ckDispose(imap)
        CkMessageSet::ckDispose(messageSet)
        ProcedureReturn
    EndIf

    numUnseen.i = CkMessageSet::ckCount(messageSet)
    Debug Str(numUnseen)

    Debug "UIDs ----"

    ; Display the UIDs
    i.i = 0
    While i < CkMessageSet::ckCount(messageSet)
        Debug Str(CkMessageSet::ckGetId(messageSet,i))
        i = i + 1
    Wend

    ; Disconnect from the IMAP server.
    success = CkImap::ckDisconnect(imap)


    CkImap::ckDispose(imap)
    CkMessageSet::ckDispose(messageSet)


    ProcedureReturn
EndProcedure