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

Scan for Emails with Attachments and Save Attachments to Files

Scan for emails with attachments and save attachments.

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('myLogin', 'myPassword');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

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

  // We can choose to fetch UIDs or sequence numbers.
  final fetchUids = true;

  // Get the message IDs of all the emails in the mailbox
  final messageSet = CkMessageSet();
  try {
    imap.queryMbx('ALL', fetchUids, messageSet);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Fetch the email headers into a bundle object:
  final bundle = CkEmailBundle();
  final headersOnly = true;
  try {
    imap.fetchMsgSet(headersOnly, messageSet, bundle);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Scan for emails with attachments, and save the attachments
  // to a sub-directory.
  final fullEmail = CkEmail();
  final emailHeader = CkEmail();
  var i = 0;
  while (i < bundle.messageCount) {
    // The bundle contains email headers..
    bundle.emailAt(i, emailHeader);

    // Does this email have attachments?
    // Use GetMailNumAttach because the attachments
    // are not actually in the email object because
    // we only downloaded headers.
    final numAttach = imap.getMailNumAttach(emailHeader);

    if (numAttach > 0) {
      // Download the entire email and save the
      // attachments. (Remember, we 
      // need to download the entire email because
      // only the headers were previously downloaded.

      // The ckx-imap-uid header field is added when
      // headers are downloaded.  This makes it possible
      // to get the UID from the email object.
      final uidStr = emailHeader.getHeaderField('ckx-imap-uid');
      final uid = int.parse(uidStr);

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

      fullEmail.saveAllAttachments('attachmentsDir');

      for (var j = 0; j < numAttach; j++) {
        final filename = imap.getMailAttachFilename(emailHeader, j);
        print(filename);
      }
    }

    i++;
  }

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