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

Sorting Email

Demonstrates how to sort an email bundle.

Chilkat Dart Downloads

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

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

  final imap = CkImap();

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

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

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

  final fetchUids = true;
  final messageSet = CkMessageSet();
  try {
    imap.queryMbx('ALL', fetchUids, messageSet);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Fetch the email headers into a bundle object:
  final bundle = CkEmailBundle();
  final headersOnly = true;
  try {
    imap.fetchMsgSet(headersOnly, messageSet, bundle);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Sort the email bundle by date, recipient, sender, or subject:
  final ascending = true;
  bundle.sortByDate(ascending);

  // To sort by recipient, sender, or subject, call 
  // SortBySender, SortByRecipient, or SortBySubject.

  // Display the Subject and From of each email.
  final email = CkEmail();
  var i = 0;
  while (i < bundle.messageCount) {
    bundle.emailAt(i, email);

    print(email.getHeaderField('Date'));
    print(email.subject);
    print(email.from);
    print('--');

    i++;
  }

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