Sample code for 30+ languages & platforms
React Native

Expunge Deleted Messages and Close the Mailbox

See more IMAP Examples

Demonstrates the Chilkat Imap.ExpungeAndClose method, which permanently removes all messages marked with \Deleted from the selected mailbox and then closes the mailbox. This example marks a message deleted and then expunges-and-closes.

Background: This combines two actions into one call: the permanent removal of \Deleted messages (see Expunge) followed by closing the mailbox (see CloseMailbox), returning the session to the authenticated-but-no-mailbox-selected state while staying connected. It's the natural way to finish working with a mailbox after cleaning it up, before selecting another or logging out.

Chilkat React Native Downloads

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

async function chilkatExample() {
  // Demonstrates the Imap.ExpungeAndClose method, which permanently removes all messages
  // marked with \Deleted from the selected mailbox and then closes the mailbox.

  const imap = new Imap();

  imap.ssl = true;
  imap.port = 993;

  try {
    await imap.connectAsync('imap.example.com');
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  try {
    await imap.loginAsync('user@example.com', 'myPassword');
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  try {
    await imap.selectMailboxAsync('Inbox');
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  // Mark message (sequence number 1) with the \Deleted flag.
  try {
    await imap.setFlagAsync(1, false, '\\Deleted', 1);
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  // Remove the \Deleted messages and close the mailbox in one step.
  try {
    await imap.expungeAndCloseAsync();
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  console.log('Expunged and closed the mailbox.');

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