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

Delete Email Individually (One at a time) from an IMAP Mailbox

Downloads email from an IMAP mailbox and deletes emails individually (one by one).

Chilkat React Native Downloads

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

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

  const imap = new Imap();

  // 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');
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  // We can choose to fetch UIDs or sequence numbers.
  const fetchUids = true;

  // Get the message IDs of all the emails in the mailbox
  const messageSet = new MessageSet();
  try {
    await imap.queryMbxAsync('ALL', fetchUids, messageSet);
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  // Fetch the emails into a bundle object:
  const bundle = new EmailBundle();
  const headersOnly = false;
  try {
    await imap.fetchMsgSetAsync(headersOnly, messageSet, bundle);
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  // To mark a complete set of emails for deletion, call SetFlags:
  try {
    await imap.setFlagsAsync(messageSet, 'Deleted', 1);
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  // Messages can also be marked for deletion individually:
  // Loop over the bundle and mark each message for deletion.
  const email = new Email();
  let i = 0;
  const numEmails = bundle.messageCount;
  while (i < numEmails) {
    bundle.emailAt(i, email);

    console.log(email.from);
    console.log(email.subject);

    // To delete this email, set the "Deleted" flag to 1.
    // The email is not actually deleted until Expunge or
    // ExpungeAndClose is called.
    try {
      await imap.setMailFlagAsync(email, 'Deleted', 1);
    } catch {
      console.log(imap.lastErrorText);
      return;
    }

    console.log('--');

    i++;
  }

  try {
    await imap.expungeAndCloseAsync();
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

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