Sample code for 30+ languages & platforms
Zig

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

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

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

    const secrets = try chilkat.Secrets.init();
    defer secrets.deinit();

    // 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.
    const json = try chilkat.JsonObject.init();
    defer json.deinit();
    json.updateString("appName", "MyEmailApp") catch {};
    json.updateString("service", "SMTP") catch {};
    json.updateString("domain", "example.com") catch {};
    json.updateString("username", "joe@example.com") catch {};

    // Create or update the secret.
    // This secret is the SMTP password for the above email account.
    secrets.updateSecretStr(json, "joes_password") catch {
        std.debug.print("{s}\n", .{try secrets.getLastErrorText(alloc)});
        return;
    };

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

    secrets.updateSecretStr(json, "janes_password") catch {
        std.debug.print("{s}\n", .{try secrets.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("Success.\n", .{});
}