Sample code for 30+ languages & platforms
Java

Set a TLS Client Certificate for IMAP

See more IMAP Examples

Demonstrates the Chilkat Imap.SetSslClientCert method, which supplies a client certificate for TLS client-certificate authentication. The only argument is a Cert object that must provide access to its private key. Call it before connecting. This example loads the certificate from a PFX file.

Note: The certificate path is relative to the application's current working directory. Supply the path to your own certificate file.

Background: Most IMAP servers authenticate with a username and password only. A few high-security deployments additionally require mutual TLS, where the client presents its own certificate during the handshake. Because that happens as part of connecting, the certificate must be set before Connect — setting it afterward has no effect on the already-established connection.

Chilkat Java Downloads

Java
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    //  Demonstrates the Imap.SetSslClientCert method, which supplies a client certificate for TLS
    //  client-certificate authentication.  The only argument is a Cert object.  It must be called
    //  before connecting.

    CkImap imap = new CkImap();

    imap.put_Ssl(true);
    imap.put_Port(993);

    //  The PFX password is not hard-coded in source.  Insert code here to obtain it from an
    //  interactive prompt, environment variable, or a secrets vault.
    String pfxPassword;

    //  Load the client certificate (and its private key) from a PFX file.
    CkCert cert = new CkCert();
    success = cert.LoadPfxFile("qa_data/client.pfx",pfxPassword);
    if (success == false) {
        System.out.println(cert.lastErrorText());
        return;
        }

    //  Provide the client certificate BEFORE connecting.
    success = imap.SetSslClientCert(cert);
    if (success == false) {
        System.out.println(imap.lastErrorText());
        return;
        }

    success = imap.Connect("imap.example.com");
    if (success == false) {
        System.out.println(imap.lastErrorText());
        return;
        }

    success = imap.Login("user@example.com","myPassword");
    if (success == false) {
        System.out.println(imap.lastErrorText());
        return;
        }

    success = imap.Disconnect();
    if (success == false) {
        System.out.println(imap.lastErrorText());
        return;
        }
  }
}