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

How to Download Messages in MessageSet One at a Time

See more IMAP Examples

If a message set contains a huge number of emails, it's NOT a good idea to try to download all at once into an email bundle using a method such as FetchBundle. It's better to iterate over the messages in the set to download one by one.

Chilkat React Native Downloads

React Native
import { Email, 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();

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

  // Authenticate
  try {
    await imap.loginAsync('email_account_login', 'email_account_password');
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

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

  // Search for messages and return a set of matching messages.
  // (This example will simply search for ALL messages.)
  const fetchUids = true;

  const messageSet = new MessageSet();
  try {
    await imap.queryMbxAsync('ALL', fetchUids, messageSet);
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  console.log(`Number of messages = ${messageSet.count}`);

  const email = new Email();
  let i = 0;
  while (i < messageSet.count) {
    try {
      await imap.fetchEmailAsync(false, messageSet.getId(i), fetchUids, email);
    } catch {
      console.log(imap.lastErrorText);
      return;
    }

    console.log(`${email.from}; ${email.subject}`);

    i++;
  }

  console.log('OK');
}