Sample code for 30+ languages & platforms
Xbase++

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 Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oEmail
LOCAL oCert
LOCAL oSbSmime
LOCAL oMailman

nSuccess := 0

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

oEmail := CreateObject("Chilkat.Email")

nSuccess := oEmail:LoadEml("c:/temp/email/unencrypted.eml")
IF (nSuccess == 0)
    ? oEmail:LastErrorText
    oEmail:destroy()
    RETURN
ENDIF

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

oCert := CreateObject("Chilkat.Cert")
nSuccess := oCert:LoadFromFile("c/temps/cert/recipient.cer")
IF (nSuccess == 0)
    ? oCert:LastErrorText
    oEmail:destroy()
    oCert:destroy()
    RETURN
ENDIF

oEmail:SendEncrypted := 1
oEmail:SetEncryptCert(oCert)

oSbSmime := CreateObject("Chilkat.StringBuilder")

//  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.
oMailman := CreateObject("Chilkat.MailMan")
nSuccess := oMailman:RenderToMimeSb(oEmail, oSbSmime)
IF (nSuccess == 0)
    ? oMailman:LastErrorText
    oEmail:destroy()
    oCert:destroy()
    oSbSmime:destroy()
    oMailman:destroy()
    RETURN
ENDIF

nSuccess := oSbSmime:WriteFile("c:/temp/encryptedEmail.eml", "utf-8", 0)
IF (nSuccess == 0)
    ? oMailman:LastErrorText
    oEmail:destroy()
    oCert:destroy()
    oSbSmime:destroy()
    oMailman:destroy()
    RETURN
ENDIF

? "Success!"

oEmail:destroy()
oCert:destroy()
oSbSmime:destroy()
oMailman:destroy()