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

Download Unread Email from IMAP Mailbox

Download unread email messages from an IMAP mailbox.

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('imap.example.com');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Login
  try {
    imap.login('admin@chilkatsoft.com', '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;
  }

  // Find emails marked as seen or not already seen:
  final seenSearch = 'SEEN';
  final notSeenSearch = 'NOT SEEN';

  // Get the set of unseen message UIDs
  final fetchUids = true;
  final messageSet = CkMessageSet();
  try {
    imap.queryMbx(notSeenSearch, fetchUids, messageSet);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

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

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

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

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