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

Delete All IMAP Email

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

Chilkat React Native Downloads

React Native
import { Imap, MessageSet } from '@chilkat/react-native'

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

  const imap = new Imap();

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

  // Connect to an IMAP server.
  // Use TLS
  imap.ssl = true;
  imap.port = 993;
  try {
    await imap.connectAsync('imap.example.com');
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  // Login
  try {
    await imap.loginAsync('myLogin', 'myPassword');
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  // Select an IMAP mailbox
  try {
    await imap.selectMailboxAsync('Inbox.RubyMail');
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  // Get the complete set of Uids for email in the selected mailbox.
  const messageSet = new MessageSet();
  try {
    await imap.queryMbxAsync('ALL', true, messageSet);
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  // Set the Deleted flag for each message.
  // (ExpungeAndClose must be called to finalize the delete.)
  try {
    await imap.setFlagsAsync(messageSet, 'Deleted', 1);
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  // Alternatively, the Deleted flag may be set for each UID
  // individiually, but this is less efficient:
  let i = 0;
  const n = messageSet.count;
  while (i < n) {
    try {
      await imap.setFlagAsync(messageSet.getId(i), messageSet.hasUids, 'Deleted', 1);
    } catch {
      console.log(imap.lastErrorText);
      return;
    }

    i++;
  }

  // Expunge and close the mailbox.
  try {
    await imap.expungeAndCloseAsync();
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

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

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