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

Delete All IMAP Email

Demonstrates two ways to delete all email in a mailbox on an IMAP server.

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();

  // Turn on session logging:
  imap.keepSessionLog = true;

  // 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('myLogin', 'myPassword');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

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

  // Get the complete set of Uids for email in the selected mailbox.
  final messageSet = CkMessageSet();
  try {
    imap.queryMbx('ALL', true, messageSet);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Set the Deleted flag for each message.
  // (ExpungeAndClose must be called to finalize the delete.)
  try {
    imap.setFlags(messageSet, 'Deleted', 1);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Alternatively, the Deleted flag may be set for each UID
  // individiually, but this is less efficient:
  var i = 0;
  final n = messageSet.count;
  while (i < n) {
    try {
      imap.setFlag(messageSet.getId(i), messageSet.hasUids, 'Deleted', 1);
    } on ChilkatException catch (e) {
      print(e.lastErrorText);
      return;
    }

    i++;
  }

  // Expunge and close the mailbox.
  try {
    imap.expungeAndClose();
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Display the session log.
  print(imap.sessionLog);

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