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

Sign and encrypt an email with S/MIME

See more Email Object Examples

Use the sender’s signing PFX and the recipient’s public RSA certificate with with-attachments.eml, which has one recipient. Supply your own signing-key password from a credential store. Render to bytes to apply both S/MIME operations without connecting to SMTP.

Chilkat Dart Downloads

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

void main() {
  // Assumes Chilkat is unlocked. See Global Unlock Sample.

  final email = CkEmail();
  try {
    email.loadEml('with-attachments.eml');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  final signer = CkCert();
  try {
    signer.loadPfxFile('signer.pfx', 'SIGNER_PASSWORD');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  final recipient = CkCert();
  try {
    recipient.loadFromFile('recipient.cer');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  try {
    email.setSigningCert(signer);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  try {
    email.setEncryptCert(recipient);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  email.signingHashAlg = 'sha256';
  email.pkcs7CryptAlg = 'aes';
  email.pkcs7KeyLength = 256;
  email.oaepPadding = true;
  email.oaepHash = 'sha256';
  email.oaepMgfHash = 'sha256';
  email.sendSigned = true;
  email.sendEncrypted = true;
  final mail = CkMailMan();
  final rendered = CkBinData();
  try {
    mail.renderToMimeBd(email, rendered);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  try {
    rendered.writeFile('signed-encrypted.eml');
  } on ChilkatException {
    print('Failed: rendered.WriteFile.');
    return;
  }

  print('Saved signed-encrypted.eml.');
}