Sample code for 30+ languages & platforms
Unicode C++

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 Unicode C++ Downloads

Unicode C++
#include <CkImapW.h>
#include <CkEmailW.h>

void ChilkatSample(void)
    {
    bool success = false;

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

    CkImapW imap;

    // Connect to an IMAP server.
    // Use TLS
    imap.put_Ssl(true);
    imap.put_Port(993);
    success = imap.Connect(L"mail.testemail.net");
    if (success == false) {
        wprintf(L"%s\n",imap.lastErrorText());
        return;
    }

    // Login
    success = imap.Login(L"***",L"***");
    if (success == false) {
        wprintf(L"%s\n",imap.lastErrorText());
        return;
    }

    // Select an IMAP mailbox
    success = imap.SelectMailbox(L"Inbox");
    if (success == false) {
        wprintf(L"%s\n",imap.lastErrorText());
        return;
    }

    // After selecting a mailbox, the NumMessages property
    // contains the number of emails in the selected mailbox.
    int n;
    n = imap.get_NumMessages();

    if (n > 0) {

        // The oldest email is always at sequence number 1.
        bool isUid = false;

        CkEmailW oldestEmail;
        success = imap.FetchEmail(false,1,isUid,oldestEmail);
        if (success == false) {
            wprintf(L"%s\n",imap.lastErrorText());
            return;
        }

        // Display the From and Subject
        wprintf(L"%s\n",oldestEmail.fromAddress());
        wprintf(L"%s\n",oldestEmail.subject());

        wprintf(L"--\n");

        // The newest email is at sequence number N:
        CkEmailW newestEmail;
        success = imap.FetchEmail(false,n,isUid,newestEmail);
        if (success == false) {
            wprintf(L"%s\n",imap.lastErrorText());
            return;
        }

        // Display the From and Subject
        wprintf(L"%s\n",newestEmail.fromAddress());
        wprintf(L"%s\n",newestEmail.subject());

    }

    // Disconnect from the IMAP server.
    success = imap.Disconnect();
    }