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

Fetch Single Email by UID or Sequence Number

Assuming the UID is known, download a single email by UID from an IMAP mail server.

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  // This example requires the Chilkat API to have been previously unlocked.
  // See Global Unlock Sample for sample code.

  final imap = CkImap();

  // Connect to an IMAP server.
  // Use TLS
  imap.ssl = true;
  imap.port = 993;
  try {
    imap.connect('imap.example.com');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Login
  try {
    imap.login('***', '***');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Select an IMAP mailbox
  try {
    imap.selectMailbox('Inbox');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  final email = CkEmail();

  final uid = 2014;
  final isUid = true;

  try {
    imap.fetchEmail(false, uid, isUid, email);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Display the From and Subject
  print(email.fromAddress);
  print(email.subject);

  // Display the Body property, which is the default body.
  // If an email has an HTML body, the Body property contains
  // the HTML source.  Otherwise it contains the plain-text
  // body.
  print('---- EMAIL BODY ----');
  print(email.body);
  print('--------------------');

  // Display the recipients:
  for (var j = 0; j < email.numTo; j++) {
    print('${email.getToName(j)}, ${email.getToAddr(j)}');
  }

  for (var j = 0; j < email.numCC; j++) {
    print('${email.getCcName(j)}, ${email.getCcAddr(j)}');
  }

  // Show the total size of the email, including body and attachments:
  print(email.size);

  // When a full email is downloaded, we would use the
  // email.NumAttachments property in conjunction with the
  // email.GetMailAttach* methods.
  // However, when an email object contains only the header,
  // we need to access the attachment info differently:
  final numAttach = imap.getMailNumAttach(email);
  print(numAttach);

  for (var j = 0; j < numAttach; j++) {
    print(imap.getMailAttachFilename(email, j));
    final attachSize = imap.getMailAttachSize(email, j);
    print('    size = $attachSize bytes');
  }

  print('--');

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