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

How to Copy IMAP Mail to another IMAP Server

Demonstrates how to copy the entire contents of an IMAP mailbox to another IMAP server.

Chilkat React Native Downloads

React Native
import { Imap, StringBuilder } 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 imapSrc = new Imap();

  // Connect to our source IMAP server.
  try {
    await imapSrc.connectAsync('imap.example.com');
  } catch {
    console.log(imapSrc.lastErrorText);
    return;
  }

  // Login to the source IMAP server
  try {
    await imapSrc.loginAsync('admin@chilkatsoft.com', 'myPassword');
  } catch {
    console.log(imapSrc.lastErrorText);
    return;
  }

  const imapDest = new Imap();

  // Connect to our destination IMAP server.
  try {
    await imapDest.connectAsync('mail.example-code.com');
  } catch {
    console.log(imapDest.lastErrorText);
    return;
  }

  // Login to the destination IMAP server
  try {
    await imapDest.loginAsync('myLogin', 'myPassword');
  } catch {
    console.log(imapDest.lastErrorText);
    return;
  }

  // Select an IMAP mailbox on the source IMAP server
  try {
    await imapSrc.selectMailboxAsync('Inbox');
  } catch {
    console.log(imapSrc.lastErrorText);
    return;
  }

  // After selecting a mailbox, the NumMessages property will
  // be updated to reflect the total number of emails in the mailbox:
  console.log(imapSrc.numMessages);

  // The emails in the mailbox will always have sequence numbers
  // ranging from 1 to NumMessages.

  // This example will copy the first 10 messages using sequence numbers
  const sbMime = new StringBuilder();
  for (let seqNum = 1; seqNum <= 10; seqNum++) {
    sbMime.clear();
    try {
      await imapSrc.fetchSingleAsMimeSbAsync(seqNum, false, sbMime);
    } catch {
      console.log(imapSrc.lastErrorText);
      return;
    }

    try {
      await imapDest.appendMimeWithFlagsSbAsync('Inbox', sbMime, false, false, false, false);
    } catch {
      console.log(imapDest.lastErrorText);
      return;
    }
  }

  // Disconnect from the IMAP servers.
  await imapSrc.disconnectAsync();
  await imapDest.disconnectAsync();
}