### Complete VaultSandbox Webhook Setup Example Source: https://vaultsandbox.dev/client-dotnet/guides/webhooks A full example demonstrating how to initialize the VaultSandbox client, create an inbox, set up a webhook with filters, test it, list existing webhooks, update a webhook, and clean up resources. ```csharp using VaultSandbox.Client; async Task SetupWebhooksAsync(CancellationToken cancellationToken) { var client = VaultSandboxClientBuilder.Create() .WithBaseUrl(Environment.GetEnvironmentVariable("VAULTSANDBOX_URL")!) .WithApiKey(Environment.GetEnvironmentVariable("VAULTSANDBOX_API_KEY")!) .Build(); try { // Create inbox var inbox = await client.CreateInboxAsync(cancellationToken: cancellationToken); Console.WriteLine($"Inbox: {inbox.EmailAddress}"); // Create webhook with filter var webhook = await inbox.CreateWebhookAsync(new CreateWebhookOptions { Url = "https://your-app.com/webhook/emails", Events = [WebhookEventType.EmailReceived, WebhookEventType.EmailStored], Description = "Production email webhook", Filter = new WebhookFilterConfig { Rules = [ new WebhookFilterRuleConfig { Field = FilterableField.FromAddress, Operator = FilterOperator.Domain, Value = "example.com" } ], Mode = FilterMode.All } }, cancellationToken); Console.WriteLine($"Webhook created: {webhook.Id}"); Console.WriteLine($"Secret: {webhook.Secret}"); // Test the webhook var testResult = await webhook.TestAsync(cancellationToken); if (testResult.Success) { Console.WriteLine("Webhook test successful!"); } else { Console.WriteLine($"Webhook test failed: {testResult.Error}"); } // List all webhooks var webhooks = await inbox.ListWebhooksAsync(cancellationToken); Console.WriteLine($"Total webhooks: {webhooks.Count}"); // Update webhook await inbox.UpdateWebhookAsync(webhook.Id, new UpdateWebhookOptions { Description = "Updated description" }, cancellationToken); // Rotate secret after some time // var rotation = await webhook.RotateSecretAsync(cancellationToken); // Cleanup // await webhook.DeleteAsync(cancellationToken); // await client.DeleteInboxAsync(inbox.EmailAddress, cancellationToken); } finally { if (client is IAsyncDisposable disposable) { await disposable.DisposeAsync(); } } } ``` -------------------------------- ### Verify VaultSandbox SDK Installation Source: https://vaultsandbox.dev/client-java/installation A Java example demonstrating how to initialize the VaultSandbox client with configuration and verify successful setup. ```java import com.vaultsandbox.client.VaultSandboxClient; import com.vaultsandbox.client.ClientConfig; public class VerifyInstallation { public static void main(String[] args) { ClientConfig config = ClientConfig.builder() .apiKey("your-api-key") .baseUrl("https://gateway.example.com") .build(); try (VaultSandboxClient client = VaultSandboxClient.create(config)) { System.out.println("VaultSandbox client initialized successfully!"); System.out.println("Bouncy Castle provider registered."); } } } ``` -------------------------------- ### Virtual Environment Setup Source: https://vaultsandbox.dev/client-python/installation Commands to initialize projects and install dependencies within isolated environments. ```bash python -m venv .venv source .venv/bin/activate # Linux/macOS # or .venv\Scripts\activate # Windows pip install vaultsandbox ``` ```bash poetry new my-project cd my-project poetry add vaultsandbox poetry shell ``` ```bash uv init my-project cd my-project uv add vaultsandbox ``` -------------------------------- ### Complete VaultSandbox Client Usage Example Source: https://vaultsandbox.dev/client-node/api/client This example demonstrates initializing the client, checking the API key, getting server info, creating an inbox, exporting it, waiting for an email, and cleaning up resources. Ensure VAULTSANDBOX_URL and VAULTSANDBOX_API_KEY environment variables are set. ```javascript import { VaultSandboxClient } from '@vaultsandbox/client'; async function main() { // Create client (SSE is the default strategy) const client = new VaultSandboxClient({ url: process.env.VAULTSANDBOX_URL, apiKey: process.env.VAULTSANDBOX_API_KEY, maxRetries: 5, }); try { // Verify API key const isValid = await client.checkKey(); if (!isValid) { throw new Error('Invalid API key'); } // Get server info const info = await client.getServerInfo(); console.log(`Connected to VaultSandbox (default TTL: ${info.defaultTtl}s)`); // Create inbox const inbox = await client.createInbox(); console.log(`Created inbox: ${inbox.emailAddress}`); // Export for later use await client.exportInboxToFile(inbox, './inbox-backup.json'); // Wait for email const email = await inbox.waitForEmail({ timeout: 30000, subject: /Test/, }); console.log(`Received: ${email.subject}`); // Clean up await inbox.delete(); // Delete any other orphaned inboxes const deleted = await client.deleteAllInboxes(); console.log(`Cleaned up ${deleted} total inboxes`); } finally { // Always close the client await client.close(); } } main().catch(console.error); ``` -------------------------------- ### Client Initialization Example Source: https://vaultsandbox.dev/client-node/api/client Example showing how to initialize the client with custom retry settings. ```typescript import { VaultSandboxClient } from '@vaultsandbox/client'; // SSE is the default strategy const client = new VaultSandboxClient({ url: 'https://smtp.vaultsandbox.com', apiKey: process.env.VAULTSANDBOX_API_KEY, maxRetries: 5, retryDelay: 2000, }); ``` -------------------------------- ### Complete Inbox Monitoring Example Source: https://vaultsandbox.dev/client-python/api/client A comprehensive example demonstrating the creation of multiple inboxes, setting up an email monitor with a handler, starting the monitor, and performing cleanup. ```python import asyncio from vaultsandbox import VaultSandboxClient, Inbox, Email async def monitor_multiple_inboxes(): async with VaultSandboxClient(api_key=api_key) as client: # Create multiple inboxes inbox1 = await client.create_inbox() inbox2 = await client.create_inbox() print(f"Inbox 1: {inbox1.email_address}") print(f"Inbox 2: {inbox2.email_address}") # Monitor both inboxes monitor = client.monitor_inboxes([inbox1, inbox2]) @monitor.on_email async def handle_email(inbox: Inbox, email: Email): print(f"\nNew email in {inbox.email_address}:") print(f" Subject: {email.subject}") print(f" From: {email.from_address}") await monitor.start() # Wait for emails to arrive... await asyncio.sleep(60) # Clean up await monitor.unsubscribe() await inbox1.delete() await inbox2.delete() asyncio.run(monitor_multiple_inboxes()) ``` -------------------------------- ### Complete Vault Sandbox Client Example in Go Source: https://vaultsandbox.dev/client-go/guides/webhooks A full example demonstrating client initialization, creating an inbox, setting up a webhook with filters and events, testing it, listing webhooks, updating, and cleanup. ```go package main import ( "context" "fmt" "log" "os" "time" "github.com/vaultsandbox/client-go" ) func main() { ctx := context.Background() client, err := vaultsandbox.New( os.Getenv("VAULTSANDBOX_API_KEY"), vaultsandbox.WithBaseURL(os.Getenv("VAULTSANDBOX_URL")), ) if err != nil { log.Fatal(err) } defer client.Close() // Create inbox inbox, err := client.CreateInbox(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Inbox: %s\n", inbox.EmailAddress()) // Create webhook with filter webhook, err := inbox.CreateWebhook(ctx, "https://your-app.com/webhook/emails", vaultsandbox.WithWebhookEvents( vaultsandbox.WebhookEventEmailReceived, vaultsandbox.WebhookEventEmailStored, ), vaultsandbox.WithWebhookDescription("Production email webhook"), vaultsandbox.WithWebhookFilter(&vaultsandbox.FilterConfig{ Rules: []vaultsandbox.FilterRule{ {Field: "from", Operator: vaultsandbox.FilterOperatorDomain, Value: "example.com"}, }, Mode: vaultsandbox.FilterModeAll, }), ) if err != nil { log.Fatal(err) } fmt.Printf("Webhook created: %s\n", webhook.ID) fmt.Printf("Secret: %s\n", webhook.Secret) // Test the webhook testResult, err := inbox.TestWebhook(ctx, webhook.ID) if err != nil { log.Fatal(err) } if testResult.Success { fmt.Println("Webhook test successful!") } else { fmt.Printf("Webhook test failed: %s\n", testResult.Error) } // List all webhooks response, err := inbox.ListWebhooks(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Total webhooks: %d\n", response.Total) // Update webhook _, err = inbox.UpdateWebhook(ctx, webhook.ID, vaultsandbox.WithUpdateDescription("Updated description"), ) if err != nil { log.Fatal(err) } // Cleanup // err = inbox.DeleteWebhook(ctx, webhook.ID) // err = inbox.Delete(ctx) } ``` -------------------------------- ### Initialize VaultSandbox Client Example Source: https://vaultsandbox.dev/client-go/api/client Example demonstrating how to initialize the VaultSandbox client with API key, custom base URL, retry count, and timeout. Ensure the VAULTSANDBOX_API_KEY environment variable is set. ```go package main import ( "os" "time" vaultsandbox "github.com/vaultsandbox/client-go" ) func main() { client, err := vaultsandbox.New( os.Getenv("VAULTSANDBOX_API_KEY"), vaultsandbox.WithBaseURL("https://api.vaultsandbox.com"), // SSE is the default strategy, no need to specify vaultsandbox.WithRetries(5), vaultsandbox.WithTimeout(30*time.Second), ) if err != nil { panic(err) } defer client.Close() } ``` -------------------------------- ### Example SSE Usage with Real-time Subscription Source: https://vaultsandbox.dev/client-dotnet/advanced/strategies Demonstrates setting up the SSE strategy and subscribing to real-time email notifications using IAsyncEnumerable. Includes an example of waiting for a specific email. ```csharp var client = VaultSandboxClientBuilder.Create() .WithBaseUrl("https://smtp.vaultsandbox.com") .WithApiKey(Environment.GetEnvironmentVariable("VAULTSANDBOX_API_KEY")!) .UseSseDelivery() .Build(); var inbox = await client.CreateInboxAsync(); // Real-time subscription using IAsyncEnumerable (uses SSE) using var cts = new CancellationTokenSource(); await foreach (var email in inbox.WatchAsync(cts.Token)) { Console.WriteLine($"Instant notification: {email.Subject}"); // Cancel after first email (or based on your logic) if (ShouldStop(email)) { cts.Cancel(); } } // Waiting also uses SSE (faster than polling) var email = await inbox.WaitForEmailAsync(new WaitForEmailOptions { Timeout = TimeSpan.FromSeconds(10), Subject = "Welcome", UseRegex = true }); ``` -------------------------------- ### Example Config File Content Source: https://vaultsandbox.dev/cli/configuration This is an example of the `config.yaml` file content, showing how API key, base URL, default output format, and strategy are stored. ```yaml api_key: your-api-key base_url: https://your-gateway.vsx.email default_output: pretty strategy: sse ``` -------------------------------- ### Install vsb-cli using Go Install Source: https://vaultsandbox.dev/cli/installation Install the vsb-cli using the Go toolchain. Requires Go 1.24 or later. ```go go install github.com/vaultsandbox/vsb-cli/cmd/vsb@latest ``` -------------------------------- ### Setup and Manage Webhooks with VaultSandbox Client Source: https://vaultsandbox.dev/client-node/guides/webhooks Use this example to create an inbox, set up a webhook with specific event filters, test its functionality, list existing webhooks, and update its configuration. Ensure your VAULTSANDBOX_URL and VAULTSANDBOX_API_KEY environment variables are set. ```javascript import { VaultSandboxClient } from '@vaultsandbox/client'; async function setupWebhooks() { const client = new VaultSandboxClient({ url: process.env.VAULTSANDBOX_URL, apiKey: process.env.VAULTSANDBOX_API_KEY, }); try { // Create inbox const inbox = await client.createInbox(); console.log(`Inbox: ${inbox.emailAddress}`); // Create webhook with filter const webhook = await inbox.createWebhook({ url: 'https://your-app.com/webhook/emails', events: ['email.received', 'email.stored'], description: 'Production email webhook', filter: { rules: [{ field: 'from', operator: 'domain', value: 'example.com' }], mode: 'all', }, }); console.log(`Webhook created: ${webhook.id}`); console.log(`Secret: ${webhook.secret}`); // Test the webhook const testResult = await inbox.testWebhook(webhook.id); if (testResult.success) { console.log('Webhook test successful!'); } else { console.error('Webhook test failed:', testResult.error); } // List all webhooks const { webhooks, total } = await inbox.listWebhooks(); console.log(`Total webhooks: ${total}`); // Update webhook await inbox.updateWebhook(webhook.id, { description: 'Updated description', }); // Rotate secret after some time // const newSecret = await inbox.rotateWebhookSecret(webhook.id); // Cleanup // await inbox.deleteWebhook(webhook.id); // await inbox.delete(); } finally { await client.close(); } } setupWebhooks().catch(console.error); ``` -------------------------------- ### Create Webhook Example Source: https://vaultsandbox.dev/client-python/api/inbox Example of creating a webhook and saving the returned signing secret. ```python webhook = await inbox.create_webhook( url="https://your-app.com/webhook/emails", events=["email.received"], description="Production email notifications", ) print(f"Webhook ID: {webhook.id}") print(f"Secret: {webhook.secret}") # Save this! ``` -------------------------------- ### Install mkcert Utility Source: https://vaultsandbox.dev/deployment/local-development Commands to install mkcert on various operating systems for local HTTPS testing. ```bash # macOS brew install mkcert # Linux sudo apt install libnss3-tools curl -JLO "https://dl.filippo.io/mkcert/latest?for=linux/amd64" chmod +x mkcert-v*-linux-amd64 sudo mv mkcert-v*-linux-amd64 /usr/local/bin/mkcert # Windows (with Chocolatey) choco install mkcert ``` -------------------------------- ### Go Testing Setup and Email Verification Source: https://vaultsandbox.dev/client-go/testing/cicd Configure Go tests with environment variable checks, client setup, and inbox creation for email testing. Includes a basic test for a welcome email. ```go package myapp_test import ( "context" "os" "regexp" "testing" "time" "github.com/vaultsandbox/client-go" ) var client *vaultsandbox.Client func TestMain(m *testing.M) { // Verify environment variables are set if os.Getenv("VAULTSANDBOX_URL") == "" { panic("VAULTSANDBOX_URL environment variable is required") } if os.Getenv("VAULTSANDBOX_API_KEY") == "" { panic("VAULTSANDBOX_API_KEY environment variable is required") } // Run tests code := m.Run() // Global cleanup if client != nil { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() deleted, err := client.DeleteAllInboxes(ctx) if err != nil { println("Failed to clean up inboxes:", err.Error()) } else if deleted > 0 { println("Cleaned up", deleted, "inboxes") } client.Close() } os.Exit(code) } func setupClient(t *testing.T) *vaultsandbox.Client { t.Helper() c, err := vaultsandbox.New( os.Getenv("VAULTSANDBOX_API_KEY"), vaultsandbox.WithBaseURL(os.Getenv("VAULTSANDBOX_URL")), vaultsandbox.WithTimeout(30*time.Second), ) if err != nil { t.Fatalf("Failed to create client: %v", err) } // Store for global cleanup client = c return c } func TestWelcomeEmail(t *testing.T) { client := setupClient(t) ctx := context.Background() inbox, err := client.CreateInbox(ctx, vaultsandbox.WithTTL(5*time.Minute)) if err != nil { t.Fatalf("Failed to create inbox: %v", err) } defer inbox.Delete(ctx) // Trigger your application to send the email sendWelcomeEmail(inbox.EmailAddress()) email, err := inbox.WaitForEmail(ctx, vaultsandbox.WithWaitTimeout(10*time.Second), vaultsandbox.WithSubjectRegex(regexp.MustCompile(`Welcome`)), ) if err != nil { t.Fatalf("Failed to receive email: %v", err) } if email.From != "noreply@example.com" { t.Errorf("Expected from noreply@example.com, got %s", email.From) } } ``` -------------------------------- ### Install Docker and Docker Compose Source: https://vaultsandbox.dev/deployment/deployment-setup Commands to verify versions and install the required Docker environment on Ubuntu/Debian systems. ```bash # Check versions docker --version docker-compose --version # or docker compose version # Install Docker (Ubuntu/Debian) curl -fsSL https://get.docker.com -o get-docker.sh sudo sh get-docker.sh # Install Docker Compose v2 (plugin) sudo apt-get update sudo apt-get install docker-compose-plugin ``` -------------------------------- ### Complete VaultSandbox Email Example Source: https://vaultsandbox.dev/client-go/api/email A comprehensive example demonstrating the VaultSandbox Go client. It covers creating an inbox, sending a test email, waiting for it, parsing details like content and attachments, checking authentication, marking as read, retrieving raw source, and cleaning up the inbox. ```go package main import ( "context" "encoding/json" "fmt" "log" "os" "regexp" "strings" "time" "github.com/vaultsandbox/client-go" ) func main() { ctx := context.Background() client, err := vaultsandbox.New( os.Getenv("VAULTSANDBOX_API_KEY"), vaultsandbox.WithBaseURL(os.Getenv("VAULTSANDBOX_URL")), ) if err != nil { log.Fatal(err) } defer client.Close() inbox, err := client.CreateInbox(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Created inbox: %s\n", inbox.EmailAddress()) // Trigger test email sendTestEmail(inbox.EmailAddress()) // Wait for email email, err := inbox.WaitForEmail(ctx, vaultsandbox.WithWaitTimeout(10*time.Second), vaultsandbox.WithSubjectRegex(regexp.MustCompile(`Test`)), ) if err != nil { log.Fatal(err) } // Basic info fmt.Println("\n=== Email Details ===") fmt.Printf("ID: %s\n", email.ID) fmt.Printf("From: %s\n", email.From) fmt.Printf("To: %s\n", strings.Join(email.To, ", ")) fmt.Printf("Subject: %s\n", email.Subject) fmt.Printf("Received: %s\n", email.ReceivedAt.Format(time.RFC3339)) fmt.Printf("Read: %v\n", email.IsRead) // Content fmt.Println("\n=== Content ===") if email.Text != "" { fmt.Println("Plain text:") if len(email.Text) > 200 { fmt.Printf("%s...\n", email.Text[:200]) } else { fmt.Println(email.Text) } } if email.HTML != "" { fmt.Println("HTML version present") } // Links fmt.Println("\n=== Links ===") fmt.Printf("Found %d links:\n", len(email.Links)) for _, link := range email.Links { fmt.Printf(" - %s\n", link) } // Attachments fmt.Println("\n=== Attachments ===") fmt.Printf("Found %d attachments:\n", len(email.Attachments)) for _, att := range email.Attachments { fmt.Printf(" - %s (%s, %d bytes)\n", att.Filename, att.ContentType, att.Size) // Save attachment if len(att.Content) > 0 { path := "./downloads/" + att.Filename if err := os.WriteFile(path, att.Content, 0644); err != nil { log.Printf("Failed to save %s: %v\n", att.Filename, err) } else { fmt.Printf(" Saved to %s\n", path) } } } // Authentication fmt.Println("\n=== Authentication ===") validation := email.AuthResults.Validate() fmt.Printf("Overall: %s\n", boolToPassFail(validation.Passed)) fmt.Printf("SPF: %v\n", validation.SPFPassed) fmt.Printf("DKIM: %v\n", validation.DKIMPassed) fmt.Printf("DMARC: %v\n", validation.DMARCPassed) if !validation.Passed { fmt.Printf("Failures: %v\n", validation.Failures) } // Mark as read if err := inbox.MarkEmailAsRead(ctx, email.ID); err != nil { log.Fatal(err) } fmt.Println("\nMarked as read") // Get raw source raw, err := inbox.GetRawEmail(ctx, email.ID) if err != nil { log.Fatal(err) } filename := fmt.Sprintf("email-%s.eml", email.ID) if err := os.WriteFile(filename, []byte(raw), 0644); err != nil { log.Fatal(err) } fmt.Printf("Saved raw source to %s\n", filename) // Clean up if err := inbox.Delete(ctx); err != nil { log.Fatal(err) } } func boolToPassFail(b bool) string { if b { return "PASS" } return "FAIL" } func sendTestEmail(address string) { // Your email sending logic here } ``` -------------------------------- ### Example JSON Configuration Output Source: https://vaultsandbox.dev/cli/configuration This is an example of the JSON output from `vsb config show -o json`, illustrating the structure for API key, base URL, strategy, and server capabilities. ```json { "apiKey": "vsb_*****", "baseUrl": "https://your-gateway.vsx.email", "strategy": "sse", "server": { "spamAnalysisEnabled": true, "allowedDomains": ["example.com", "test.com"] } } ``` -------------------------------- ### Complete Email Processing Example Source: https://vaultsandbox.dev/client-python/api/email A full workflow example including inbox creation, email retrieval, content inspection, authentication validation, and cleanup. ```python import asyncio import os import re from vaultsandbox import VaultSandboxClient, WaitForEmailOptions async def complete_email_example(): async with VaultSandboxClient( api_key=os.environ["VAULTSANDBOX_API_KEY"], ) as client: inbox = await client.create_inbox() print(f"Created inbox: {inbox.email_address}") # Trigger test email await send_test_email(inbox.email_address) # Wait for email email = await inbox.wait_for_email( WaitForEmailOptions( timeout=10000, subject=re.compile(r"Test"), ) ) # Basic info print("\n=== Email Details ===") print(f"ID: {email.id}") print(f"From: {email.from_address}") print(f"To: {', '.join(email.to)}") print(f"Subject: {email.subject}") print(f"Received: {email.received_at.isoformat()}") print(f"Read: {email.is_read}") # Content print("\n=== Content ===") if email.text: print("Plain text:") print(email.text[:200] + "...") if email.html: print("HTML version present") # Links print("\n=== Links ===") print(f"Found {len(email.links)} links:") for link in email.links: print(f" - {link}") # Attachments print("\n=== Attachments ===") print(f"Found {len(email.attachments)} attachments:") for att in email.attachments: print(f" - {att.filename} ({att.content_type}, {att.size} bytes)") # Save attachment with open(f"./downloads/{att.filename}", "wb") as f: f.write(att.content) print(f" Saved to ./downloads/{att.filename}") # Authentication print("\n=== Authentication ===") validation = email.auth_results.validate() print(f"Overall: {'PASS' if validation.passed else 'FAIL'}") if email.auth_results.spf: print(f"SPF: {email.auth_results.spf.result.value}") if email.auth_results.dkim: print(f"DKIM: {email.auth_results.dkim[0].result.value}") if email.auth_results.dmarc: print(f"DMARC: {email.auth_results.dmarc.result.value}") if not validation.passed: print("Failures:", validation.failures) # Mark as read await email.mark_as_read() print("\nMarked as read") # Get raw source raw_email = await email.get_raw() with open(f"email-{raw_email.id}.eml", "w") as f: f.write(raw_email.raw) print(f"Saved raw source to email-{raw_email.id}.eml") # Clean up await inbox.delete() asyncio.run(complete_email_example()) ``` -------------------------------- ### Complete Chaos Example Source: https://vaultsandbox.dev/client-java/guides/chaos This example shows how to enable and configure various chaos features like latency and random errors when creating an inbox. It also demonstrates how to retrieve, update, and disable chaos configurations. ```java import com.vaultsandbox.client.VaultSandboxClient; import com.vaultsandbox.client.Inbox; import com.vaultsandbox.client.CreateInboxOptions; import com.vaultsandbox.client.model.*; public class ChaosExample { public static void main(String[] args) { VaultSandboxClient client = VaultSandboxClient.builder() .url(System.getenv("VAULTSANDBOX_URL")) .apiKey(System.getenv("VAULTSANDBOX_API_KEY")) .build(); try { // Check if chaos is available ServerInfo serverInfo = client.getServerInfo(); if (!serverInfo.isChaosEnabled()) { System.out.println("Chaos features not available on this server"); return; } // Create inbox with chaos enabled ChaosConfig chaos = ChaosConfig.builder() .enabled(true) .latency(LatencyConfig.builder() .enabled(true) .minDelayMs(2000) .maxDelayMs(5000) .probability(0.5) .build()) .randomError(RandomErrorConfig.builder() .enabled(true) .errorRate(0.1) .errorTypes(ChaosErrorType.TEMPORARY) .build()) .build(); Inbox inbox = client.createInbox( CreateInboxOptions.builder() .chaos(chaos) .build() ); System.out.println("Testing with chaos: " + inbox.getEmailAddress()); // Get current chaos configuration ChaosConfig config = inbox.getChaos(); System.out.println("Chaos enabled: " + config.isEnabled()); if (config.getLatency() != null) { System.out.println("Latency enabled: " + config.getLatency().isEnabled()); } // Send test emails and verify handling // Your test logic here... // Update chaos configuration inbox.setChaos(ChaosConfig.builder() .enabled(true) .greylist(GreylistConfig.builder() .enabled(true) .maxAttempts(3) .build()) .build()); // More testing... // Disable chaos for normal operation tests inbox.disableChaos(); // Clean up inbox.delete(); } finally { client.close(); } } } ``` -------------------------------- ### Complete Client Usage Example Source: https://vaultsandbox.dev/client-go/api/client A full workflow demonstrating client initialization, inbox creation, email waiting, and cleanup. ```go package main import ( "context" "fmt" "log" "os" "regexp" "time" vaultsandbox "github.com/vaultsandbox/client-go" ) func main() { ctx := context.Background() // Create client client, err := vaultsandbox.New( os.Getenv("VAULTSANDBOX_API_KEY"), vaultsandbox.WithBaseURL(os.Getenv("VAULTSANDBOX_URL")), // SSE is the default strategy vaultsandbox.WithRetries(5), ) if err != nil { log.Fatal(err) } defer client.Close() // Verify API key if err := client.CheckKey(ctx); err != nil { log.Fatal("Invalid API key:", err) } // Get server info info := client.ServerInfo() fmt.Printf("Connected to VaultSandbox (default TTL: %v)\n", info.DefaultTTL) // Create inbox inbox, err := client.CreateInbox(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Created inbox: %s\n", inbox.EmailAddress()) // Export for later use if err := client.ExportInboxToFile(inbox, "./inbox-backup.json"); err != nil { log.Fatal(err) } // Wait for email email, err := inbox.WaitForEmail(ctx, vaultsandbox.WithWaitTimeout(30*time.Second), vaultsandbox.WithSubjectRegex(regexp.MustCompile(`Test`)), ) if err != nil { log.Fatal(err) } fmt.Printf("Received: %s\n", email.Subject) // Clean up if err := inbox.Delete(ctx); err != nil { log.Fatal(err) } // Delete any other orphaned inboxes deleted, err := client.DeleteAllInboxes(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Cleaned up %d total inboxes\n", deleted) } ``` -------------------------------- ### Get Webhook Example Source: https://vaultsandbox.dev/client-python/api/inbox Retrieve a webhook and display its delivery statistics. ```python webhook = await inbox.get_webhook("whk_abc123") print(f"URL: {webhook.url}") print(f"Enabled: {webhook.enabled}") print(f"Last delivery: {webhook.last_delivery_at or 'Never'}") if webhook.stats: print(f"Deliveries: {webhook.stats.successful_deliveries}/{webhook.stats.total_deliveries}") ``` -------------------------------- ### Run Interactive Configuration Wizard Source: https://vaultsandbox.dev/cli/configuration Use this command to launch the interactive setup wizard. It will prompt for your API key and gateway URL and save them to the config file. ```bash vsb config ``` -------------------------------- ### Complete Inbox Example Workflow Source: https://vaultsandbox.dev/client-go/api/inbox A comprehensive example demonstrating the full lifecycle of an inbox, including creation, watching for emails, sending test emails, waiting for specific emails, marking as read, exporting, and cleanup. Requires VAULTSANDBOX_API_KEY and VAULTSANDBOX_URL environment variables. ```go package main import ( "context" "encoding/json" "fmt" "log" "os" "regexp" "time" "github.com/vaultsandbox/client-go" ) func completeInboxExample() error { ctx := context.Background() client, err := vaultsandbox.New( os.Getenv("VAULTSANDBOX_API_KEY"), vaultsandbox.WithBaseURL(os.Getenv("VAULTSANDBOX_URL")), ) if err != nil { return err } defer client.Close() // Create inbox inbox, err := client.CreateInbox(ctx) if err != nil { return err } fmt.Printf("Created: %s\n", inbox.EmailAddress()) fmt.Printf("Expires: %s\n", inbox.ExpiresAt().Format(time.RFC3339)) // Set up watching in a goroutine watchCtx, cancelWatch := context.WithCancel(ctx) go func() { for email := range inbox.Watch(watchCtx) { fmt.Printf("Received via watch: %s\n", email.Subject) } }() // Trigger test email err = sendTestEmail(inbox.EmailAddress()) if err != nil { return err } // Wait for specific email email, err := inbox.WaitForEmail(ctx, vaultsandbox.WithWaitTimeout(10*time.Second), vaultsandbox.WithSubjectRegex(regexp.MustCompile(`Test`)), ) if err != nil { return err } fmt.Printf("Found email: %s\n", email.Subject) fmt.Printf("Body: %s\n", email.Text) // Mark as read err = inbox.MarkEmailAsRead(ctx, email.ID) if err != nil { return err } // Get all emails allEmails, err := inbox.GetEmails(ctx) if err != nil { return err } fmt.Printf("Total emails: %d\n", len(allEmails)) // Export inbox exportData := inbox.Export() jsonData, err := json.Marshal(exportData) if err != nil { return err } err = os.WriteFile("inbox.json", jsonData, 0600) if err != nil { return err } // Clean up cancelWatch() err = inbox.Delete(ctx) if err != nil { return err } return nil } func main() { if err := completeInboxExample(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Environment Variable Setup Source: https://vaultsandbox.dev/client-go/configuration Configuration using .env files and loading them in Go. ```bash VAULTSANDBOX_URL=https://mail.example.com VAULTSANDBOX_API_KEY=vs_1234567890abcdef... ``` ```go import ( "os" "github.com/joho/godotenv" "github.com/vaultsandbox/client-go" ) func main() { // Load .env file godotenv.Load() client, err := vaultsandbox.New(os.Getenv("VAULTSANDBOX_API_KEY"), vaultsandbox.WithBaseURL(os.Getenv("VAULTSANDBOX_URL")), ) if err != nil { log.Fatal(err) } defer client.Close() } ``` -------------------------------- ### Server Information Response Source: https://vaultsandbox.dev/sdk/client-spec Example JSON response from the GET /api/server-info endpoint containing cryptographic configuration. ```json { "serverSigPk": "", "algs": { "kem": "ML-KEM-768", "sig": "ML-DSA-65", "aead": "AES-256-GCM", "kdf": "HKDF-SHA-512" }, "context": "vaultsandbox:email:v1", "encryptionPolicy": "always", "maxTtl": 604800, "defaultTtl": 3600, "sseConsole": false, "allowedDomains": ["vaultsandbox.test", "example.com"] } ``` -------------------------------- ### JUnit 5 Setup and Teardown with Vault Sandbox Source: https://vaultsandbox.dev/client-java/guides/managing-inboxes Demonstrates JUnit 5 setup and teardown methods for initializing and cleaning up Vault Sandbox client and inbox resources. API key and base URL should be configured via environment variables. ```java class EmailTest { private VaultSandboxClient client; private Inbox inbox; @BeforeEach void setUp() { ClientConfig config = ClientConfig.builder() .apiKey(System.getenv("VAULTSANDBOX_API_KEY")) .baseUrl(System.getenv("VAULTSANDBOX_URL")) .build(); client = VaultSandboxClient.create(config); inbox = client.createInbox(); } @AfterEach void tearDown() { if (inbox != null) { try { inbox.delete(); } catch (Exception ignored) {} } if (client != null) { client.close(); } } @Test void shouldReceiveWelcomeEmail() { // Trigger email signUpUser(inbox.getEmailAddress()); // Wait and verify Email email = inbox.waitForEmail( EmailFilter.subjectContains("Welcome"), Duration.ofSeconds(30) ); assertThat(email.getFrom()).isEqualTo("noreply@example.com"); } } ``` -------------------------------- ### Test password reset flow Source: https://vaultsandbox.dev/client-go/concepts/inboxes Example of a complete test cycle including setup, email waiting, and assertions. ```go func TestPasswordReset(t *testing.T) { client, err := vaultsandbox.New(os.Getenv("VAULTSANDBOX_API_KEY")) if err != nil { t.Fatal(err) } defer client.Close() ctx := context.Background() inbox, err := client.CreateInbox(ctx, vaultsandbox.WithTTL(2*time.Hour)) if err != nil { t.Fatal(err) } defer inbox.Delete(context.Background()) // Trigger password reset triggerPasswordReset(inbox.EmailAddress()) // Wait for email email, err := inbox.WaitForEmail(ctx, vaultsandbox.WithWaitTimeout(10*time.Second), ) if err != nil { t.Fatal(err) } // Assertions if email.Subject != "Password Reset" { t.Errorf("expected subject 'Password Reset', got %q", email.Subject) } } ``` -------------------------------- ### Quick Example: VaultSandbox Go Client Source: https://vaultsandbox.dev/client-go Demonstrates creating a client, generating an inbox, waiting for an email, and cleaning up. Ensure you replace 'your-api-key' and the base URL with your actual credentials and server address. ```go package main import ( "context" "fmt" "log" "time" "github.com/vaultsandbox/client-go" ) func main() { client, err := vaultsandbox.New("your-api-key", vaultsandbox.WithBaseURL("https://gateway.example.com"), ) if err != nil { log.Fatal(err) } defer client.Close() ctx := context.Background() // Create inbox (keypair generated automatically) inbox, err := client.CreateInbox(ctx) if err != nil { log.Fatal(err) } // Send email to inbox.EmailAddress() from your application... // Wait for email email, err := inbox.WaitForEmail(ctx, vaultsandbox.WithWaitTimeout(30*time.Second), ) if err != nil { log.Fatal(err) } fmt.Println("Subject:", email.Subject) fmt.Println("Text:", email.Text) // Cleanup if err := inbox.Delete(ctx); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Set JAVA_HOME Environment Variable Source: https://vaultsandbox.dev/client-java/installation Example command to set the JAVA_HOME environment variable to point to a Java 21 installation. ```bash export JAVA_HOME=/path/to/java21 ``` -------------------------------- ### Application Metrics Response (JSON) Source: https://vaultsandbox.dev/gateway/api-reference This is an example JSON response for the 'get /api/metrics' endpoint, detailing various server metrics. ```json { "connections": { "total": 150, "active": 5, "rejected": 2 }, "inbox": { "created_total": 42, "deleted_total": 12, "active_total": 30 }, "email": { "received_total": 1024, "recipients_total": 1256, "processing_time_ms": 150 }, "rejections": { "invalid_commands": 3, "sender_rejected_total": 5, "recipient_rejected_total": 8, "data_rejected_size_total": 2, "hard_mode_total": 0, "rate_limit_total": 1 }, "auth": { "spf_pass": 980, "spf_fail": 44, "dkim_pass": 950, "dkim_fail": 74, "dmarc_pass": 920, "dmarc_fail": 104 }, "certificate": { "days_until_expiry": 45, "renewal_attempts": 3, "renewal_success": 3, "renewal_failures": 0 }, "server": { "uptime_seconds": 86400 }, "spam": { "analyzed_total": 980, "skipped_total": 44, "errors_total": 2, "spam_detected_total": 15, "processing_time_ms": 4500 } } ``` -------------------------------- ### Docker Compose Configuration for Rspamd Source: https://vaultsandbox.dev/gateway/spam-analysis Example setup for running the Gateway and Rspamd services together using Docker Compose. ```yaml services: gateway: image: vaultsandbox/gateway:latest container_name: vaultsandbox-gateway restart: unless-stopped ports: - '25:25' # SMTP - '80:80' # HTTP (ACME challenges) - '443:443' # HTTPS (Web UI + API) environment: VSB_VSX_DNS_ENABLED: 'true' VSB_ENCRYPTION_ENABLED: 'enabled' # Spam Analysis - Rspamd integration VSB_SPAM_ANALYSIS_ENABLED: 'true' VSB_RSPAMD_URL: 'http://rspamd:11333' VSB_RSPAMD_TIMEOUT_MS: '5000' # VSB_RSPAMD_PASSWORD: 'optional-password' # Only if Rspamd has auth enabled VSB_SPAM_ANALYSIS_INBOX_DEFAULT: 'true' volumes: - gateway-data:/app/data depends_on: - rspamd rspamd: image: rspamd/rspamd:latest container_name: rspamd restart: unless-stopped # Web UI only on localhost (not exposed publicly) ports: - '127.0.0.1:11334:11334' volumes: - rspamd-data:/var/lib/rspamd volumes: gateway-data: rspamd-data: ``` -------------------------------- ### Customized Health Check Behavior Source: https://vaultsandbox.dev/deployment/docker-compose Example of customizing health check parameters like interval, timeout, retries, and start period. ```yaml healthcheck: interval: 60s # Check every 60 seconds timeout: 5s # Timeout after 5 seconds retries: 5 # Retry 5 times before marking unhealthy start_period: 60s # Wait 60s before starting checks ``` -------------------------------- ### Configure client with advanced options Source: https://vaultsandbox.dev/client-java/api/client Demonstrates using environment variables, custom strategies, and resource cleanup with try-with-resources. ```java ClientConfig config = ClientConfig.builder() .apiKey(System.getenv("VAULTSANDBOX_API_KEY")) .baseUrl(System.getenv("VAULTSANDBOX_URL")) .strategy(StrategyType.SSE) .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()); } ``` -------------------------------- ### Initialize Client with Full Configuration Source: https://vaultsandbox.dev/client-dotnet/configuration Configures the client manually using the builder pattern with all available settings. ```csharp var client = VaultSandboxClientBuilder.Create() .WithBaseUrl("https://gateway.example.com") .WithApiKey("api-key") .WithHttpTimeout(TimeSpan.FromSeconds(60)) .WithWaitTimeout(TimeSpan.FromMinutes(2)) .WithPollInterval(TimeSpan.FromSeconds(1)) .WithMaxRetries(5) .WithRetryDelay(TimeSpan.FromSeconds(2)) .WithSseReconnectInterval(TimeSpan.FromSeconds(2)) .WithSseMaxReconnectAttempts(15) .UseSseDelivery() .WithDefaultInboxTtl(TimeSpan.FromMinutes(30)) .Build(); ``` -------------------------------- ### Get a Specific Email Source: https://vaultsandbox.dev/client-node/concepts/inboxes Retrieve a single email from the inbox using its unique ID. The example logs the subject and text content of the retrieved email. ```javascript const email = await inbox.getEmail('email-id-123'); console.log(email.subject); console.log(email.text); ``` -------------------------------- ### Install VaultSandbox Go Client Source: https://vaultsandbox.dev/client-go/installation Use `go get` to add the VaultSandbox client library to your project. This command automatically updates your `go.mod` file. ```go go get github.com/vaultsandbox/client-go ``` -------------------------------- ### Development Configuration Example Source: https://vaultsandbox.dev/client-dotnet/configuration Client configuration optimized for local development environments. ```csharp var client = VaultSandboxClientBuilder.Create() .WithBaseUrl("http://localhost:3000") .WithApiKey("dev-api-key") .WithPollInterval(TimeSpan.FromMilliseconds(500)) .WithMaxRetries(1) .UsePollingDelivery() .Build(); ``` -------------------------------- ### Get and Print Sender Email Address Source: https://vaultsandbox.dev/client-go/api/email Waits for an email, prints its sender address, and includes an example of verifying the sender's address against an expected value. ```go email, err := inbox.WaitForEmail(ctx, vaultsandbox.WithWaitTimeout(10*time.Second)) if err != nil { log.Fatal(err) } fmt.Printf("From: %s\n", email.From) if email.From != "noreply@example.com" { t.Errorf("expected from noreply@example.com, got %s", email.From) } ``` -------------------------------- ### Initialize Client from Environment Variables Source: https://vaultsandbox.dev/client-dotnet/configuration Initializes the client by reading configuration directly from environment variables. ```csharp var client = VaultSandboxClientBuilder.Create() .WithBaseUrl(Environment.GetEnvironmentVariable("VAULTSANDBOX_URL")!) .WithApiKey(Environment.GetEnvironmentVariable("VAULTSANDBOX_API_KEY")!) .Build(); ```