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

Sign and encrypt an email with S/MIME

See more Email Object Examples

Use the sender’s signing PFX and the recipient’s public RSA certificate with with-attachments.eml, which has one recipient. Supply your own signing-key password from a credential store. Render to bytes to apply both S/MIME operations without connecting to SMTP.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oEmail
LOCAL oSigner
LOCAL oRecipient
LOCAL oMail
LOCAL oRendered

nSuccess := 0

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

oEmail := CreateObject("Chilkat.Email")
nSuccess := oEmail:LoadEml("with-attachments.eml")
IF (nSuccess != 1)
    ? oEmail:LastErrorText
    oEmail:destroy()
    RETURN
ENDIF

oSigner := CreateObject("Chilkat.Cert")
nSuccess := oSigner:LoadPfxFile("signer.pfx", "SIGNER_PASSWORD")
IF (nSuccess != 1)
    ? oSigner:LastErrorText
    oEmail:destroy()
    oSigner:destroy()
    RETURN
ENDIF

oRecipient := CreateObject("Chilkat.Cert")
nSuccess := oRecipient:LoadFromFile("recipient.cer")
IF (nSuccess != 1)
    ? oRecipient:LastErrorText
    oEmail:destroy()
    oSigner:destroy()
    oRecipient:destroy()
    RETURN
ENDIF

nSuccess := oEmail:SetSigningCert(oSigner)
IF (nSuccess != 1)
    ? oEmail:LastErrorText
    oEmail:destroy()
    oSigner:destroy()
    oRecipient:destroy()
    RETURN
ENDIF

nSuccess := oEmail:SetEncryptCert(oRecipient)
IF (nSuccess != 1)
    ? oEmail:LastErrorText
    oEmail:destroy()
    oSigner:destroy()
    oRecipient:destroy()
    RETURN
ENDIF

oEmail:SigningHashAlg := "sha256"
oEmail:Pkcs7CryptAlg := "aes"
oEmail:Pkcs7KeyLength := 256
oEmail:OaepPadding := 1
oEmail:OaepHash := "sha256"
oEmail:OaepMgfHash := "sha256"
oEmail:SendSigned := 1
oEmail:SendEncrypted := 1
oMail := CreateObject("Chilkat.MailMan")
oRendered := CreateObject("Chilkat.BinData")
nSuccess := oMail:RenderToMimeBd(oEmail, oRendered)
IF (nSuccess != 1)
    ? oMail:LastErrorText
    oEmail:destroy()
    oSigner:destroy()
    oRecipient:destroy()
    oMail:destroy()
    oRendered:destroy()
    RETURN
ENDIF

nSuccess := oRendered:WriteFile("signed-encrypted.eml")
IF (nSuccess != 1)
    ? "Failed: rendered.WriteFile."
    oEmail:destroy()
    oSigner:destroy()
    oRecipient:destroy()
    oMail:destroy()
    oRendered:destroy()
    RETURN
ENDIF

? "Saved signed-encrypted.eml."

oEmail:destroy()
oSigner:destroy()
oRecipient:destroy()
oMail:destroy()
oRendered:destroy()