Sample code for 30+ languages & platforms
PureBasic

Use a TLS Client Certificate

See more SMTP Examples

Demonstrates the Chilkat MailMan.SetSslClientCert method, which sets the client-side certificate to use for SSL/TLS connections. This is typically not required — most SSL/TLS connections authenticate the server only. This example loads a client certificate from a PFX and uses it when connecting.

Background: In an ordinary TLS handshake only the server presents a certificate, and the client proves who it is later with a password. Mutual TLS adds a second leg: the client also presents a certificate, so it is authenticated cryptographically at the transport layer. Some corporate or high-security mail servers require this. Because the client must prove possession of the key, the certificate needs its private key — hence loading from a PFX.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkMailMan.pb"
IncludeFile "CkCert.pb"

Procedure ChilkatExample()

    success.i = 0

    ;  Demonstrates the MailMan.SetSslClientCert method, which sets the client-side certificate
    ;  to use for SSL/TLS connections.  This is typically not required -- most SSL/TLS
    ;  connections authenticate the server only.

    mailman.i = CkMailMan::ckCreate()
    If mailman.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ;  Configure the SMTP server connection.
    CkMailMan::setCkSmtpHost(mailman, "smtp.example.com")
    CkMailMan::setCkSmtpPort(mailman, 465)
    CkMailMan::setCkSmtpSsl(mailman, 1)
    CkMailMan::setCkSmtpUsername(mailman, "user@example.com")
    CkMailMan::setCkSmtpPassword(mailman, "myPassword")

    ;  Load the client certificate (with its private key) from a PFX file.
    cert.i = CkCert::ckCreate()
    If cert.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkCert::ckLoadPfxFile(cert,"qa_data/certs/client.pfx","pfx_password")
    If success = 0
        Debug CkCert::ckLastErrorText(cert)
        CkMailMan::ckDispose(mailman)
        CkCert::ckDispose(cert)
        ProcedureReturn
    EndIf

    ;  Use this certificate to identify the client during the TLS handshake.
    success = CkMailMan::ckSetSslClientCert(mailman,cert)
    If success = 0
        Debug CkMailMan::ckLastErrorText(mailman)
        CkMailMan::ckDispose(mailman)
        CkCert::ckDispose(cert)
        ProcedureReturn
    EndIf

    success = CkMailMan::ckVerifySmtpLogin(mailman)
    If success = 0
        Debug CkMailMan::ckLastErrorText(mailman)
        CkMailMan::ckDispose(mailman)
        CkCert::ckDispose(cert)
        ProcedureReturn
    EndIf

    Debug "Connected using a TLS client certificate."

    ;  Note: The path "qa_data/certs/client.pfx" is a relative local filesystem path,
    ;  relative to the current working directory of the running application.


    CkMailMan::ckDispose(mailman)
    CkCert::ckDispose(cert)


    ProcedureReturn
EndProcedure