Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

Set the Recipient Encryption Certificate

See more Email Object Examples

Demonstrates the Chilkat Email.SetEncryptCert method, which sets the explicit recipient encryption certificate for sending an encrypted email. This example loads the recipient's certificate, sets it, and enables encrypted sending.

Background: To encrypt a message for a recipient you need their public certificate — hence a .cer file (no private key) suffices. SetEncryptCert specifies a single recipient certificate; to encrypt for multiple recipients, use AddEncryptCert once per certificate. Either way, setting SendEncrypted to true is what actually requests encryption when the message is sent.

Chilkat Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.Email,
  Chilkat.Cert;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  email: TEmail;
  cert: TCert;

begin
  success := False;

  //  Demonstrates the SetEncryptCert method, which sets the explicit recipient encryption
  //  certificate for sending an encrypted email.

  email := TEmail.Create;
  email.Subject := 'Encrypted email';
  email.Body := 'This message will be sent S/MIME encrypted.';
  email.From := 'alice@example.com';
  email.AddTo('Bob','bob@example.com');

  //  Load the recipient's certificate (only the public key is needed to encrypt).
  cert := TCert.Create;
  success := cert.LoadFromFile('qa_data/certs/recipient.cer');
  if (success = False) then
    begin
      WriteLn(cert.LastErrorText);
      Exit;
    end;

  //  Set the explicit recipient encryption certificate.
  success := email.SetEncryptCert(cert);
  if (success = False) then
    begin
      WriteLn(email.LastErrorText);
      Exit;
    end;

  //  Request encrypted sending.
  email.SendEncrypted := True;

  WriteLn('Encryption certificate set.');

  //  Note: The path "qa_data/certs/recipient.cer" is a relative local filesystem path,
  //  relative to the current working directory of the running application.


  email.Free;
  cert.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.