Sample code for 30+ languages & platforms
React Native

Get IMAP Attachment Sizes

See more IMAP Examples

Demonstrates the Chilkat Imap.GetMailAttachSize method, which returns the size in bytes of an attachment. The first argument is the Email and the second is the zero-based attachment index. This example fetches headers only and prints each attachment's name and size.

Background: Like the attachment filename, the size comes from ckx-imap-* metadata and is available from a header-only fetch without downloading the body. A client can therefore show attachment sizes in a message preview, and decide whether to auto-download or prompt before pulling a large file.

Chilkat React Native Downloads

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

async function chilkatExample() {
  // Demonstrates the Imap.GetMailAttachSize method, which returns the size in bytes 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;
  }

  const numAttach = imap.getMailNumAttach(email);
  for (let i = 0; i < numAttach; i++) {
    let fname: string;
    try {
      fname = imap.getMailAttachFilename(email, i);
    } catch {
      console.log(imap.lastErrorText);
      return;
    }

    const sz = imap.getMailAttachSize(email, i);
    console.log(`${fname}: ${sz} bytes`);
  }

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