Sample code for 30+ languages & platforms
React Native

Get IMAP Attachment Filenames

See more IMAP Examples

Demonstrates the Chilkat Imap.GetMailAttachFilename method, which returns the filename of an attachment. The first argument is the Email and the second is the zero-based attachment index. This example fetches only the message headers and lists the attachment filenames.

Background: This method reads the filename from ckx-imap-* metadata, so it works on a header-only email even though the attachment bodies have not been downloaded. That is exactly what a mail client needs to render the paperclip list — the names of the attached files — before the user decides to download any of them.

Chilkat React Native Downloads

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

async function chilkatExample() {
  // Demonstrates the Imap.GetMailAttachFilename method, which returns the filename of an
  // attachment.  The 1st argument is the Email and the 2nd is the zero-based attachment index.

  const imap = new Imap();

  imap.ssl = true;
  imap.port = 993;

  try {
    await imap.connectAsync('imap.example.com');
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  try {
    await imap.loginAsync('user@example.com', 'myPassword');
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

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

  // Fetch only the message headers.  Attachment bodies are NOT downloaded, but the ckx-imap-*
  // metadata describing the attachments is present, so the attachment info methods still work.
  const headersOnly = true;
  const useUid = false;
  const seqNum = 1;
  const email = new Email();
  try {
    await imap.fetchEmailAsync(headersOnly, seqNum, useUid, email);
  } catch {
    console.log(imap.lastErrorText);
    return;
  }

  // Loop over the attachments and print each filename.
  const numAttach = imap.getMailNumAttach(email);
  console.log(`Attachments: ${numAttach}`);
  for (let i = 0; i < numAttach; i++) {
    // GetMailAttachFilename returns a string, so assign it to a string variable.
    let fname: string;
    try {
      fname = imap.getMailAttachFilename(email, i);
    } catch {
      console.log(imap.lastErrorText);
      return;
    }

    console.log(fname);
  }

  try {
    await imap.disconnectAsync();
  } catch {
    console.log(imap.lastErrorText);
    return;
  }
}