Sample code for 30+ languages & platforms
DataFlex

Send an Email S/MIME Encrypted

See more Email Object Examples

Demonstrates the Chilkat Email.SendEncrypted property. Set it to true to have the email sent S/MIME encrypted (the default is false). Setting this property alone is not enough — encryption requires one or more recipient certificates, supplied with AddEncryptCert or SetEncryptCert. This example loads a recipient certificate, registers it, and enables encrypted sending.

Background: To encrypt a message for someone, you need their public certificate — which is why only a .cer file (no private key) is required here. The message is scrambled so that only the holder of the matching private key, i.e. the intended recipient, can read it. When there are multiple recipients, you add each one's certificate, and Chilkat encrypts the one-time content key separately for each so they can all decrypt the same message.

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoEmail
    Variant vCert
    Handle hoCert
    String sTemp1
    Boolean bTemp1

    Move False To iSuccess

    //  Demonstrates the Email.SendEncrypted property.  Set to true to have the email sent
    //  S/MIME encrypted.  Encryption also requires one or more recipient certificates,
    //  supplied via AddEncryptCert or SetEncryptCert.  The default is false.

    Get Create (RefClass(cComChilkatEmail)) To hoEmail
    If (Not(IsComObjectCreated(hoEmail))) Begin
        Send CreateComObject of hoEmail
    End
    Set ComSubject Of hoEmail To "Encrypted email"
    Set ComBody Of hoEmail To "This message will be sent S/MIME encrypted."
    Set ComFrom Of hoEmail To "alice@example.com"
    Get ComAddTo Of hoEmail "Bob" "bob@example.com" To iSuccess

    //  Load the recipient's certificate (only the public key is needed to encrypt).
    Get Create (RefClass(cComChilkatCert)) To hoCert
    If (Not(IsComObjectCreated(hoCert))) Begin
        Send CreateComObject of hoCert
    End
    Get ComLoadFromFile Of hoCert "qa_data/certs/recipient.cer" To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoCert To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  Supply the recipient certificate used for encryption.
    Get pvComObject of hoCert to vCert
    Get ComAddEncryptCert Of hoEmail vCert To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoEmail To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  Request that the email be sent encrypted.
    Set ComSendEncrypted Of hoEmail To True

    Get ComSendEncrypted Of hoEmail To bTemp1
    Showln "SendEncrypted = " bTemp1

    //  Note: Paths such as "qa_data/..." are relative local filesystem paths,
    //  relative to the current working directory of the running application.


End_Procedure