Pascal (Lazarus/Delphi)
Pascal (Lazarus/Delphi)
S/MIME Encrypt .eml without Sending
See more Email Object Examples
Demonstrates how to encrypt an email using the recipient's digital certificate. This example just encrypts, and does not send the email.Chilkat Pascal (Lazarus/Delphi) Downloads
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.StringBuilder,
Chilkat.Cert,
Chilkat.Email;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
email: TEmail;
cert: TCert;
sbSmime: TStringBuilder;
mailman: TMailMan;
begin
success := False;
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
email := TEmail.Create;
success := email.LoadEml('c:/temp/email/unencrypted.eml');
if (success = False) then
begin
WriteLn(email.LastErrorText);
Exit;
end;
// The email content is encrypted using AES with a 256-bit key, operating in GCM mode, which provides authenticated encryption.
email.Pkcs7CryptAlg := 'aes-gcm';
email.Pkcs7KeyLength := 256;
email.OaepPadding := True;
email.OaepHash := 'sha256';
email.OaepMgfHash := 'sha256';
cert := TCert.Create;
success := cert.LoadFromFile('c/temps/cert/recipient.cer');
if (success = False) then
begin
WriteLn(cert.LastErrorText);
Exit;
end;
email.SendEncrypted := True;
email.SetEncryptCert(cert);
sbSmime := TStringBuilder.Create;
// The mailman object applies the encryption by rendering the email according to the instructions (property settings) provided in the email object.
// No email is sent.
mailman := TMailMan.Create;
success := mailman.RenderToMimeSb(email,sbSmime);
if (success = False) then
begin
WriteLn(mailman.LastErrorText);
Exit;
end;
success := sbSmime.WriteFile('c:/temp/encryptedEmail.eml','utf-8',False);
if (success = False) then
begin
WriteLn(mailman.LastErrorText);
Exit;
end;
WriteLn('Success!');
email.Free;
cert.Free;
sbSmime.Free;
mailman.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.