Sample code for 30+ languages & platforms
Java

Save Email Credentials in Apple Keychain or Windows Credentials Manager

See more Apple Keychain Examples

This example demonstrates how to save (or update) email credentials in the Apple Keychain.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Secrets;

public class ChilkatExample {

    public static void main(String[] args) {
        // This example requires the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        Secrets secrets = new Secrets();

        // On Windows, this is the Windows Credentials Manager
        // On MacOS/iOS, it is the Apple Keychain
        secrets.setLocation("local_manager");

        // Specify the name of the secret.
        // service and username are required.
        // appName and domain are optional.
        // Note: The values are arbitrary and can be anything you want.
        JsonObject json = new JsonObject();
        json.updateString("appName", "MyEmailApp");
        json.updateString("service", "SMTP");
        json.updateString("domain", "example.com");
        json.updateString("username", "joe@example.com");

        // Create or update the secret.
        // This secret is the SMTP password for the above email account.
        try {
            secrets.updateSecretStr(json, "joes_password");

            // Let's save the IMAP secret for an account we'll read using IMAP..
            json.updateString("appName", "MyEmailApp");
            json.updateString("service", "IMAP");
            json.updateString("domain", "example2.com");
            json.updateString("username", "jane@example2.com");

            secrets.updateSecretStr(json, "janes_password");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println("Success.");
    }
}