Skip to content

VaultSandboxClient API

The VaultSandboxClient is the main entry point for interacting with VaultSandbox. It handles inbox creation, email retrieval, cryptographic operations, and resource management.

public final class VaultSandboxClient implements Closeable

The client is thread-safe and can be shared across multiple threads. It uses ConcurrentHashMap for inbox registry and thread-safe HTTP clients.

Creates a client with custom configuration.

public static VaultSandboxClient create(ClientConfig config)

Parameters:

  • config - ClientConfig with all settings

Returns: Configured VaultSandboxClient instance

Throws:

  • NullPointerException - if config or config.apiKey is null

Example:

ClientConfig config = ClientConfig.builder()
.apiKey("your-api-key")
.strategy(StrategyType.SSE)
.waitTimeout(Duration.ofSeconds(60))
.build();
VaultSandboxClient client = VaultSandboxClient.create(config);

Full configuration options using the builder pattern:

ClientConfig config = ClientConfig.builder()
.apiKey("your-api-key") // Required
.baseUrl("https://...") // Optional
.strategy(StrategyType.AUTO) // Optional
.httpTimeout(Duration.ofSeconds(30))
.waitTimeout(Duration.ofSeconds(30))
.maxRetries(3)
.retryDelay(Duration.ofSeconds(1))
.retryOn(Set.of(408, 429, 500, 502, 503, 504))
.sseReconnectInterval(Duration.ofSeconds(5))
.sseMaxReconnectAttempts(10)
.pollInterval(Duration.ofSeconds(2))
.maxBackoff(Duration.ofSeconds(30))
.backoffMultiplier(1.5)
.jitterFactor(0.3)
.build();
PropertyTypeDefaultDescription
apiKeyStringrequiredAPI authentication key
baseUrlStringrequiredAPI base URL
strategyStrategyTypeAUTODelivery strategy (AUTO, SSE, POLLING)
httpTimeoutDuration30sHTTP request timeout
waitTimeoutDuration30sDefault wait timeout for emails
maxRetriesint3Max retry attempts for failed requests
retryDelayDuration1sInitial retry delay
retryOnSet<Integer>408, 429, 500-504HTTP status codes to retry
sseReconnectIntervalDuration5sSSE reconnect interval
sseMaxReconnectAttemptsint10Max SSE reconnection attempts
pollIntervalDuration2sPolling interval
maxBackoffDuration30sMax backoff duration
backoffMultiplierdouble1.5Backoff multiplier
jitterFactordouble0.3Jitter factor (0-1)

Creates a new inbox with a unique email address.

public Inbox createInbox()
public Inbox createInbox(CreateInboxOptions options)

Parameters:

  • options - Optional creation options (email address, TTL)

Returns: New Inbox instance ready to receive emails

Throws:

  • ApiException - on API errors
  • NetworkException - on network connectivity issues

Examples:

// Default options
Inbox inbox = client.createInbox();
// With custom options
CreateInboxOptions options = CreateInboxOptions.builder()
.emailAddress("[email protected]")
.ttl(Duration.ofHours(1))
.build();
Inbox inbox = client.createInbox(options);
OptionTypeDefaultDescription
emailAddressStringauto-generatedCustom email address or domain
ttlDurationserver defaultInbox time-to-live

Returns a previously created inbox by email address.

public Inbox getInbox(String emailAddress)

Parameters:

  • emailAddress - Email address of the inbox

Returns: The Inbox, or null if not found in client’s registry

Note: Only returns inboxes created or imported by this client instance.

Deletes an inbox and all its emails.

public void deleteInbox(String emailAddress)

Parameters:

  • emailAddress - Email address of inbox to delete

Throws:

  • InboxNotFoundException - if inbox doesn’t exist
  • ApiException - on API errors
  • NetworkException - on network connectivity issues

Example:

client.deleteInbox("[email protected]");

Deletes all inboxes associated with the API key.

public int deleteAllInboxes()

Returns: Number of inboxes deleted

Throws:

  • ApiException - on API errors
  • NetworkException - on network connectivity issues

Example:

int count = client.deleteAllInboxes();
System.out.println("Deleted " + count + " inbox(es)");

Exports inbox credentials for later import.

public ExportedInbox exportInbox(Inbox inbox)
public ExportedInbox exportInbox(String emailAddress)

Parameters:

  • inbox - Inbox to export, or
  • emailAddress - Email address of inbox to export

Returns: ExportedInbox containing credentials

Throws:

  • InboxNotFoundException - if inbox not found (email address variant)

Security Warning: The exported data contains private cryptographic keys. Store securely!

Example:

ExportedInbox exported = client.exportInbox(inbox);
// Store exported data securely

Exports inbox credentials to a JSON file.

public void exportInboxToFile(Inbox inbox, Path path) throws IOException

Parameters:

  • inbox - Inbox to export
  • path - File path to write

Throws:

  • IOException - on file write errors

Example:

client.exportInboxToFile(inbox, Path.of("inbox-backup.json"));

Imports a previously exported inbox.

public Inbox importInbox(ExportedInbox data) throws InvalidImportDataException

Parameters:

  • data - Exported inbox data

Returns: Restored Inbox instance

Throws:

  • InvalidImportDataException - if data is invalid or inbox no longer exists
  • InboxAlreadyExistsException - if inbox already registered with this client

Example:

ExportedInbox data = // load from storage
Inbox inbox = client.importInbox(data);

Imports inbox from a JSON file.

public Inbox importInboxFromFile(Path path) throws IOException, InvalidImportDataException

Parameters:

  • path - Path to exported JSON file

Returns: Restored Inbox instance

Throws:

  • IOException - on file read errors
  • InvalidImportDataException - if data is invalid or inbox no longer exists
  • InboxAlreadyExistsException - if inbox already registered with this client

Example:

Inbox inbox = client.importInboxFromFile(Path.of("inbox-backup.json"));

Creates a monitor for multiple inboxes.

public InboxMonitor monitorInboxes(Inbox... inboxes)
public InboxMonitor monitorInboxes(List<Inbox> inboxes)

Parameters:

  • inboxes - Inboxes to monitor (varargs or List)

Returns: InboxMonitor for registering callbacks

Example:

Inbox inbox1 = client.createInbox();
Inbox inbox2 = client.createInbox();
try (InboxMonitor monitor = client.monitorInboxes(inbox1, inbox2)) {
monitor.onEmail(email -> {
System.out.println("Email to: " + email.getTo());
System.out.println("Subject: " + email.getSubject());
});
// Trigger emails to be sent...
// Callbacks invoked as emails arrive
}
MethodDescription
onEmail(Consumer<Email>)Register callback for incoming emails
removeCallback(Consumer<Email>)Remove a registered callback
getInboxes()Get list of monitored inboxes
close()Close monitor and release resources

Gets server capabilities and configuration.

public ServerInfo getServerInfo()

Returns: ServerInfo with algorithms, limits, allowed domains

Throws:

  • ApiException - on API errors
  • NetworkException - on network connectivity issues

Note: Server info is cached after first call.

Example:

ServerInfo info = client.getServerInfo();
System.out.println("Max TTL: " + info.getMaxTtl());
System.out.println("Allowed domains: " + info.getAllowedDomains());
PropertyTypeDescription
serverSigPkStringServer’s public signing key
contextStringServer context identifier
maxTtlintMaximum inbox TTL in seconds
defaultTtlintDefault inbox TTL in seconds
sseConsolebooleanWhether SSE console is enabled (getter: isSseConsole())
allowedDomainsList<String>Allowed email domains
algorithmsAlgorithmsSupported cryptographic algorithms
versionStringServer version
domainStringServer domain
limitsLimitsRate limits and constraints

The Algorithms object contains the cryptographic algorithms used by the server:

PropertyTypeDescriptionExample
kemStringKey encapsulation mechanism"ML-KEM-768"
sigStringDigital signature algorithm"ML-DSA-65"
aeadStringAuthenticated encryption"AES-256-GCM"
kdfStringKey derivation function"HKDF-SHA-512"

Example:

ServerInfo info = client.getServerInfo();
Algorithms algs = info.getAlgorithms();
if (algs != null) {
System.out.println("KEM: " + algs.getKem()); // ML-KEM-768
System.out.println("Sig: " + algs.getSig()); // ML-DSA-65
System.out.println("AEAD: " + algs.getAead()); // AES-256-GCM
System.out.println("KDF: " + algs.getKdf()); // HKDF-SHA-512
}

The Limits object contains rate limit information:

PropertyTypeDescription
maxInboxesintMaximum number of inboxes per API key
maxEmailsPerInboxintMaximum emails per inbox
inboxTtlSecondsintDefault inbox TTL in seconds

Example:

ServerInfo info = client.getServerInfo();
ServerInfo.Limits limits = info.getLimits();
if (limits != null) {
System.out.println("Max inboxes: " + limits.getMaxInboxes());
System.out.println("Max emails per inbox: " + limits.getMaxEmailsPerInbox());
}

Validates the API key with the server.

public boolean checkKey()

Returns: true if key is valid, false if unauthorized

Throws:

  • ApiException - on unexpected API errors (other than 401)
  • NetworkException - on network connectivity issues

Example:

if (client.checkKey()) {
System.out.println("API key is valid");
} else {
System.out.println("API key is invalid");
}

Returns the client’s configuration.

public ClientConfig getConfig()

Returns: The ClientConfig used by this client

Closes the client and releases resources.

public void close()

Closes SSE connections, stops polling threads, and clears the inbox registry. Inboxes on the server are not deleted.

Usage with try-with-resources (preferred):

ClientConfig config = ClientConfig.builder()
.apiKey(apiKey)
.baseUrl(baseUrl)
.build();
try (VaultSandboxClient client = VaultSandboxClient.create(config)) {
Inbox inbox = client.createInbox();
Email email = inbox.waitForEmail();
// Process email
}
// Client automatically closed

Manual close:

ClientConfig config = ClientConfig.builder()
.apiKey(apiKey)
.baseUrl(baseUrl)
.build();
VaultSandboxClient client = VaultSandboxClient.create(config);
try {
Inbox inbox = client.createInbox();
Email email = inbox.waitForEmail();
// Process email
} finally {
client.close();
}

All exceptions extend VaultSandboxException (a RuntimeException):

ExceptionDescription
VaultSandboxExceptionBase exception type
ApiExceptionAPI returned an error (has getStatusCode())
NetworkExceptionNetwork connectivity issues
TimeoutExceptionOperation timed out
InboxNotFoundExceptionInbox doesn’t exist
InboxAlreadyExistsExceptionInbox already exists (import)
InvalidImportDataExceptionInvalid export data
EmailNotFoundExceptionEmail doesn’t exist
SseExceptionSSE connection failed
DecryptionExceptionEmail decryption failed
SignatureVerificationExceptionSignature verification failed
try {
Inbox inbox = client.createInbox();
Email email = inbox.waitForEmail(Duration.ofSeconds(30));
} catch (TimeoutException e) {
System.err.println("Email not received within timeout");
} catch (ApiException e) {
System.err.println("API error: " + e.getMessage() + " (status: " + e.getStatusCode() + ")");
} catch (NetworkException e) {
System.err.println("Network error: " + e.getMessage());
} catch (VaultSandboxException e) {
System.err.println("VaultSandbox error: " + e.getMessage());
}
ClientConfig config = ClientConfig.builder()
.apiKey("your-api-key")
.baseUrl("https://gateway.example.com")
.build();
VaultSandboxClient client = VaultSandboxClient.create(config);
try {
Inbox inbox = client.createInbox();
System.out.println("Inbox: " + inbox.getEmailAddress());
// Send email to inbox.getEmailAddress() from your application
Email email = inbox.waitForEmail();
System.out.println("Subject: " + email.getSubject());
System.out.println("Body: " + email.getText());
} finally {
client.close();
}
ClientConfig config = ClientConfig.builder()
.apiKey(System.getenv("VAULTSANDBOX_API_KEY"))
.baseUrl(System.getenv("VAULTSANDBOX_URL"))
.strategy(StrategyType.AUTO)
.waitTimeout(Duration.ofSeconds(60))
.maxRetries(5)
.build();
try (VaultSandboxClient client = VaultSandboxClient.create(config)) {
Inbox inbox = client.createInbox(
CreateInboxOptions.builder()
.ttl(Duration.ofHours(2))
.build()
);
Email email = inbox.waitForEmail();
// Process email...
client.deleteInbox(inbox.getEmailAddress());
}
ClientConfig config = ClientConfig.builder()
.apiKey(apiKey)
.baseUrl(baseUrl)
.build();
try (VaultSandboxClient client = VaultSandboxClient.create(config)) {
Inbox inbox1 = client.createInbox();
Inbox inbox2 = client.createInbox();
Inbox inbox3 = client.createInbox();
try (InboxMonitor monitor = client.monitorInboxes(inbox1, inbox2, inbox3)) {
List<Email> received = new CopyOnWriteArrayList<>();
monitor.onEmail(received::add);
// Trigger your application to send emails...
// Wait for expected emails
while (received.size() < 3) {
Thread.sleep(100);
}
// Verify all emails received
assertEquals(3, received.size());
}
client.deleteAllInboxes();
}
ClientConfig config = ClientConfig.builder()
.apiKey(apiKey)
.baseUrl(baseUrl)
.build();
// Session 1: Create and export
try (VaultSandboxClient client = VaultSandboxClient.create(config)) {
Inbox inbox = client.createInbox();
System.out.println("Created: " + inbox.getEmailAddress());
// Export for later
client.exportInboxToFile(inbox, Path.of("inbox.json"));
}
// Session 2: Import and use
try (VaultSandboxClient client = VaultSandboxClient.create(config)) {
Inbox inbox = client.importInboxFromFile(Path.of("inbox.json"));
System.out.println("Imported: " + inbox.getEmailAddress());
// Can now receive and read emails
Email email = inbox.waitForEmail();
}

VaultSandboxClient is fully thread-safe:

  • Uses ConcurrentHashMap for inbox registry
  • HTTP client (OkHttp) is thread-safe
  • Multiple threads can share one client instance
  • Delivery strategies are thread-safe

Recommended: Create one client per test class and share across test methods.