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

Copy an Email from One Mailbox to Another

Copies an email from one IMAP folder to another. After running this example, copies of the email will be present in both source and destination folders.

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.

  // This example copies an email from one mailbox to another.
  final imap = CkImap();

  // Turn on session logging:
  imap.keepSessionLog = true;

  // 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.testing.a');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  final fetchUids = true;

  // Get the message IDs for all emails having "Re:" in the subject.
  final messageSet = CkMessageSet();
  try {
    imap.queryMbx('SUBJECT Re:', fetchUids, messageSet);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Copy the messages from "Inbox.testing.a" to "Inbox.testing.b" in one call to CopyMultiple:
  try {
    imap.copyMultiple(messageSet, 'Inbox.testing.b');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Alternatively, loop over each message in the set and
  // copy each separately:
  var i = 0;
  while (i < messageSet.count) {

    final msgId = messageSet.getId(i);
    final isUid = messageSet.hasUids;

    try {
      imap.copy(msgId, isUid, 'Inbox.testing.c');
    } on ChilkatException catch (e) {
      print(e.lastErrorText);
      return;
    }

    i++;
  }

  // Display the session log.
  print(imap.sessionLog);

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