Sample code for 30+ languages & platforms
DataFlex

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

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Variant vEmail
    Handle hoEmail
    Variant vCert
    Handle hoCert
    Variant vSbSmime
    Handle hoSbSmime
    Handle hoMailman
    String sTemp1

    Move False To iSuccess

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

    Get Create (RefClass(cComChilkatEmail)) To hoEmail
    If (Not(IsComObjectCreated(hoEmail))) Begin
        Send CreateComObject of hoEmail
    End

    Get ComLoadEml Of hoEmail "c:/temp/email/unencrypted.eml" To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoEmail To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    // The email content is encrypted using AES with a 256-bit key, operating in GCM mode, which provides authenticated encryption.
    Set ComPkcs7CryptAlg Of hoEmail To "aes-gcm"
    Set ComPkcs7KeyLength Of hoEmail To 256
    Set ComOaepPadding Of hoEmail To True
    Set ComOaepHash Of hoEmail To "sha256"
    Set ComOaepMgfHash Of hoEmail To "sha256"

    Get Create (RefClass(cComChilkatCert)) To hoCert
    If (Not(IsComObjectCreated(hoCert))) Begin
        Send CreateComObject of hoCert
    End
    Get ComLoadFromFile Of hoCert "c/temps/cert/recipient.cer" To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoCert To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Set ComSendEncrypted Of hoEmail To True
    Get pvComObject of hoCert to vCert
    Get ComSetEncryptCert Of hoEmail vCert To iSuccess

    Get Create (RefClass(cComChilkatStringBuilder)) To hoSbSmime
    If (Not(IsComObjectCreated(hoSbSmime))) Begin
        Send CreateComObject of hoSbSmime
    End

    // 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.
    Get Create (RefClass(cComChilkatMailMan)) To hoMailman
    If (Not(IsComObjectCreated(hoMailman))) Begin
        Send CreateComObject of hoMailman
    End
    Get pvComObject of hoEmail to vEmail
    Get pvComObject of hoSbSmime to vSbSmime
    Get ComRenderToMimeSb Of hoMailman vEmail vSbSmime To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoMailman To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get ComWriteFile Of hoSbSmime "c:/temp/encryptedEmail.eml" "utf-8" False To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoMailman To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Showln "Success!"


End_Procedure