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

IMAP Download and Verify Signed MIME

See more IMAP Examples

Downloads the original MIME of a digitally signed email and saves the .p7s signature along with other MIME parts. It then imports the email into a Chilkat email object to unwrap the S/MIME and verify the signature, and subsequently saves the attachments if they haven't been saved already.

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;
  }

  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;
  }

  // Download the 1st email (as MIME) in the Inbox by sequence number.
  final sbMime = CkStringBuilder();
  try {
    imap.fetchSingleAsMimeSb(1, false, sbMime);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Load it into a MIME object and check to see if it is signed
  final mime = CkMime();
  mime.loadMimeSb(sbMime);
  var alreadySavedParts = false;
  if (mime.containsSignedParts()) {

    // This will save the .p7s and other parts...
    final st = CkStringTable();
    try {
      mime.partsToFiles('c:/temp/qa_output', st);
      final numFiles = st.count;
      var i = 0;
      while (i < numFiles) {
        print('Created: ${st.stringAt(i)}');
        i++;
      }

      alreadySavedParts = true;
    } on ChilkatException {
      // mime.partsToFiles() failed; continue anyway.
    }
  }

  // Load the MIME into an Email object.  This unwraps the security layers and verifies signatures.
  final email = CkEmail();
  email.setFromMimeSb(sbMime);

  if (email.receivedSigned) {
    print('This email was signed.');

    // Check to see if the signatures were verified.
    if (email.signaturesValid) {
      print('Digital signature(s) verified.');
      print('Signer: ${email.signedBy}');

      // The certificate used for signing may be obtained
      // by calling email.LastSignerCert.  Index 0 is the first signer.
      final cert = CkCert();
      try {
        email.lastSignerCert(0, cert);
        print('Signing cert: ${cert.subjectCN}');
      } on ChilkatException {
        print('Failed to get signing certificate object.');
      }
    } else {
      print('Digital signature verification failed.');
    }
  } else {
    print('This email was not signed.');
  }

  if (!alreadySavedParts) {
    email.saveAllAttachments('c:/temp/qa_output');
  }
}