Sample code for 30+ languages & platforms
React Native

Upload (Append) Email to an IMAP Mailbox and get the UID of the Appended Email

Upload / append an email to an IMAP mailbox and get the UID of the appended email.

Chilkat React Native Downloads

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

async function chilkatExample() {
  // This example assumes 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('myLogin', 'myPassword');
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  // Check the capabilities of the IMAP server.
  const cap = await imap.capabilityAsync();
  console.log(`IMAP capabilities: ${cap}`);

  // If the capabilities string contains the substring "UIDPLUS", then 
  // the UID of the appended email will be available in the AppendUid property (see below).

  // For example, the GMail IMAP server has these capabilities (at this current time)
  // * CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN 
  // X-GM-EXT-1 UIDPLUS COMPRESS=DEFLATE ENABLE MOVE CONDSTORE ESEARCH UTF8=ACCEPT 
  // APPENDLIMIT=35882577 LIST-EXTENDED LIST-STATUS

  const email = new Email();

  // Load the email from a .eml file.
  try {
    email.loadEml('myEmail.eml');
  } catch {
    console.log(email.lastErrorText);
    return;
  }

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

  // If the IMAP server supports the UIDPLUS extension, then the 
  // imap.AppendUid will contain the UID of the appended email.
  // Otherwise AppendUid will be 0.
  console.log(`UID of appended email: ${imap.appendUid}`);

  // If the IMAP server does NOT have UIDPLUS, then a program can 
  // first select the mailbox, get the value of the UidNext property,
  // and then append.  The appended email SHOULD have a UID equal to 
  // the UidNext that was obtained just prior to appending (assuming no other
  // program is simultaneously appending an email to the same mailbox).

  // Note: It is not required to select a mailbox to append.  The select is only
  // done for the purpose of obtaining the UIDNEXT value.
  try {
    await imap.selectMailboxAsync('Inbox');
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  const uidNext = imap.uidNext;

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

  console.log(`The UID of the appended email SHOULD be ${uidNext}`);

  console.log('Email uploaded to Inbox!');

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