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

Copy an Email from One Mailbox to Another

Copies an email from one IMAP folder to another. After running this example, copies of the email will be present in both source and destination folders.

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.

  // This example copies an email from one mailbox to another.
  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('***', '***');
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

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

  const fetchUids = true;

  // Get the message IDs for all emails having "Re:" in the subject.
  const messageSet = new MessageSet();
  try {
    await imap.queryMbxAsync('SUBJECT Re:', fetchUids, messageSet);
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  // Copy the messages from "Inbox.testing.a" to "Inbox.testing.b" in one call to CopyMultiple:
  try {
    await imap.copyMultipleAsync(messageSet, 'Inbox.testing.b');
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  // Alternatively, loop over each message in the set and
  // copy each separately:
  let i = 0;
  while (i < messageSet.count) {

    const msgId = messageSet.getId(i);
    const isUid = messageSet.hasUids;

    try {
      await imap.copyAsync(msgId, isUid, 'Inbox.testing.c');
    } catch {
      console.log(imap.lastErrorText);
      return;
    }

    i++;
  }

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

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