Sample code for 30+ languages & platforms
Dart Requires Chilkat v11.0.0+

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

Dart
import 'package:chilkat/chilkat.dart';

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

  final imap = CkImap();

  // Connect to an IMAP server.
  // Use TLS
  imap.ssl = true;
  imap.port = 993;
  try {
    imap.connect('mail.testemail.net');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Login
  try {
    imap.login('***', '***');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Select an IMAP mailbox
  try {
    imap.selectMailbox('Inbox');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // After selecting a mailbox, the NumMessages property
  // contains the number of emails in the selected mailbox.
  final n = imap.numMessages;

  if (n > 0) {

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

    final oldestEmail = CkEmail();
    try {
      imap.fetchEmail(false, 1, isUid, oldestEmail);
    } on ChilkatException catch (e) {
      print(e.lastErrorText);
      return;
    }

    // Display the From and Subject
    print(oldestEmail.fromAddress);
    print(oldestEmail.subject);

    print('--');

    // The newest email is at sequence number N:
    final newestEmail = CkEmail();
    try {
      imap.fetchEmail(false, n, isUid, newestEmail);
    } on ChilkatException catch (e) {
      print(e.lastErrorText);
      return;
    }

    // Display the From and Subject
    print(newestEmail.fromAddress);
    print(newestEmail.subject);
  }

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