Sample code for 30+ languages & platforms
Lianja

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 Lianja Downloads

Lianja
llSuccess = .F.

// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

loEmail = createobject("CkEmail")

llSuccess = loEmail.LoadEml("c:/temp/email/unencrypted.eml")
if (llSuccess = .F.) then
    ? loEmail.LastErrorText
    release loEmail
    return
endif

// The email content is encrypted using AES with a 256-bit key, operating in GCM mode, which provides authenticated encryption.
loEmail.Pkcs7CryptAlg = "aes-gcm"
loEmail.Pkcs7KeyLength = 256
loEmail.OaepPadding = .T.
loEmail.OaepHash = "sha256"
loEmail.OaepMgfHash = "sha256"

loCert = createobject("CkCert")
llSuccess = loCert.LoadFromFile("c/temps/cert/recipient.cer")
if (llSuccess = .F.) then
    ? loCert.LastErrorText
    release loEmail
    release loCert
    return
endif

loEmail.SendEncrypted = .T.
loEmail.SetEncryptCert(loCert)

loSbSmime = createobject("CkStringBuilder")

// 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.
loMailman = createobject("CkMailMan")
llSuccess = loMailman.RenderToMimeSb(loEmail,loSbSmime)
if (llSuccess = .F.) then
    ? loMailman.LastErrorText
    release loEmail
    release loCert
    release loSbSmime
    release loMailman
    return
endif

llSuccess = loSbSmime.WriteFile("c:/temp/encryptedEmail.eml","utf-8",.F.)
if (llSuccess = .F.) then
    ? loMailman.LastErrorText
    release loEmail
    release loCert
    release loSbSmime
    release loMailman
    return
endif

? "Success!"


release loEmail
release loCert
release loSbSmime
release loMailman