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

Create an encrypted S/MIME file without SMTP

See more Email Object Examples

Encrypt a saved draft for a recipient with an RSA encryption certificate. This example uses AES-256-GCM for the content and RSA-OAEP for the content-encryption key. Confirm these choices are supported by the receiving mail client. RenderToMimeBd produces the protected bytes without submitting mail.

Chilkat Lazarus Pascal Downloads

Lazarus Pascal
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.MailMan,
  Chilkat.BinData,
  Chilkat.Cert,
  Chilkat.Email;

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

procedure RunDemo;
var
  success: Boolean;
  email: TEmail;
  cert: TCert;
  mail: TMailMan;
  rendered: TBinData;

begin
  success := False;

  //  Assumes Chilkat is unlocked. See Global Unlock Sample.

  email := TEmail.Create;
  success := email.LoadEml('message.eml');
  if (success <> True) then
    begin
      WriteLn(email.LastErrorText);
      Exit;
    end;
  //  Use the recipient's public encryption certificate. Its private key stays with the recipient.
  cert := TCert.Create;
  success := cert.LoadFromFile('recipient.cer');
  if (success <> True) then
    begin
      WriteLn(cert.LastErrorText);
      Exit;
    end;
  success := email.SetEncryptCert(cert);
  if (success <> True) then
    begin
      WriteLn(email.LastErrorText);
      Exit;
    end;
  email.Pkcs7CryptAlg := 'aes-gcm';
  email.Pkcs7KeyLength := 256;
  email.OaepPadding := True;
  email.OaepHash := 'sha256';
  email.OaepMgfHash := 'sha256';
  email.SendEncrypted := True;
  mail := TMailMan.Create;
  rendered := TBinData.Create;
  success := mail.RenderToMimeBd(email,rendered);
  if (success <> True) then
    begin
      WriteLn(mail.LastErrorText);
      Exit;
    end;
  success := rendered.WriteFile('encrypted.eml');
  if (success <> True) then
    begin
      WriteLn('Failed: rendered.WriteFile.');
      Exit;
    end;
  WriteLn('Saved encrypted.eml.');


  email.Free;
  cert.Free;
  mail.Free;
  rendered.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.