Sample code for 30+ languages & platforms
React Native

Determine the Number of Unseen Email Messages

Demonstrates how to determine how many unseen messages exist in an email account on an IMAP server.

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.

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

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

  // After selecting the mailbox. the total number of emails
  // is immediately available:
  const totalNum = imap.numMessages;
  console.log(`Num messages = ${totalNum}`);

  // To determine the number of unseen messages, a call
  // to Search is required, which returns the set of UIDs
  // of all unseen messages.

  // We can choose to fetch UIDs or sequence numbers.
  const fetchUids = true;
  const messageSet = new MessageSet();
  try {
    await imap.queryMbxAsync('UNSEEN', fetchUids, messageSet);
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  const numUnseen = messageSet.count;
  console.log(numUnseen);

  console.log('UIDs ----');

  // Display the UIDs
  let i = 0;
  while (i < messageSet.count) {
    console.log(messageSet.getId(i));
    i++;
  }

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