# Paubox CLI authentication Source: https://docs.paubox.com/cli/authentication Log in, log out, and check credential status with the Paubox CLI. Keys are stored in your OS keychain or a local config file. The CLI authenticates against authenticated Paubox endpoints (such as the [Paubox Email API](/email-api)) using your API key. Run `paubox auth login` once and your API key is stored securely; you won't need to pass it on every command. Follow the [Paubox Email API Quickstart Guide](/email-api/quickstart) to get your API key. ## Commands | Command | Description | | :- | :- | | `paubox auth login` | Prompt for your API key, validate, and store it | | `paubox auth set-forms-key` | Prompt for a Forms API key (a scoped key with the `forms` scope) and store it | | `paubox auth logout` | Remove stored credentials, including the Forms API key | | `paubox auth status` | Show whether credentials are currently stored | ## auth login ```bash theme={null} paubox auth login ``` ``` ✔ API key: ******************************** Validating credentials… ✓ Authenticated (API key: ****abcd, stored in OS keychain) ``` The CLI validates your API key against the Paubox API before saving it. If validation fails, nothing is stored and an error is shown. ## auth set-forms-key ```bash theme={null} paubox auth set-forms-key ``` ``` ✔ Forms API key (scoped key with the 'forms' scope): ******************************** ✓ Forms API key saved (****wxyz, stored in OS keychain) ``` The Forms admin commands (`paubox forms list`, `create`, `update`, `submissions`, `webhooks`, and the rest) use this key. It is stored alongside your Email API key, and `paubox auth login` keeps it in place. ## auth logout ```bash theme={null} paubox auth logout ``` ``` ✓ Credentials removed. ``` This removes the stored credentials from wherever they were saved (keychain or config file), including the Forms API key. Run `paubox auth set-forms-key` again after logging back in. ## auth status ```bash theme={null} paubox auth status ``` ``` ✓ Authenticated (API key: ****abcd, stored in OS keychain) Forms API key: not set. Run `paubox auth set-forms-key`. ``` `auth status` reads stored credentials only; it does not call the Paubox API. If no credentials are stored: ``` Not authenticated. Run `paubox auth login`. ``` ## Where credentials are stored | Platform | Storage location | | :- | :- | | macOS | macOS Keychain | | Windows | Windows Credential Vault | | Linux (with libsecret) | Secret Service (GNOME Keyring / KWallet) | | Any platform without keychain support | `~/.config/paubox/config.json`, created with `0600` permissions (`%APPDATA%\paubox\config.json` on Windows, where those permissions don't apply) | > [!WARNING] > > If your system falls back to file-based storage, never commit `~/.config/paubox/config.json` to source control. Add it to your `.gitignore` if your home directory is under version control. > [!NOTE] > > The CLI reads credentials only from the keychain or config file written by `paubox auth login` and `paubox auth set-forms-key`. It does not read an API key from an environment variable or a command-line flag, and both commands prompt interactively. > [!NOTE] > > `paubox forms get` and `paubox forms submit` call public Paubox Forms endpoints and do not require `paubox auth login`. # Commands Source: https://docs.paubox.com/cli/commands Reference for every Paubox CLI command and global option, including auth, send, schedule, status, config, receiving, forms, and webhooks, with flags, examples, and exit codes. ## paubox auth Store, check, and remove credentials. See [Authentication](/cli/authentication) for details and sample output. | Subcommand | Description | | :- | :- | | `paubox auth login` | Prompt for your Email API key, validate it, and store it | | `paubox auth set-forms-key` | Prompt for a Forms API key (a scoped key with the `forms` scope) and store it | | `paubox auth logout` | Remove stored credentials | | `paubox auth status` | Show which keys are stored and where | *** ## paubox send Send a single HIPAA compliant email. ```bash theme={null} paubox send --to --subject [options] ``` ### Flags | Flag | Required | Description | | :- | :- | :- | | `--to ` | Yes | Recipient email address. Repeat for multiple recipients: `--to a@example.com --to b@example.com` | | `--subject ` | Yes | Email subject line | | `--html ` | One of `--html` or `--text` | HTML message body | | `--text ` | One of `--html` or `--text` | Plain-text message body | | `--from ` | No | Sender address. Defaults to `defaultFrom` from config if set. Must be on a verified Paubox domain | | `--attachment ` | No | Path to a file to attach. Repeat for multiple attachments | ### Example ```bash theme={null} paubox send \ --to patient@example.com \ --from provider@yourclinic.com \ --subject "Your appointment summary" \ --html "

See attached for your visit notes.

" \ --attachment ./visit-notes.pdf ``` ### Output ``` ✓ Email sent. Tracking ID: abc123-def456 ``` > [!TIP] > > Add `--json` to get machine-readable output instead of the human-readable success line. Useful for capturing the tracking ID in scripts and CI pipelines. The underlying API call is documented in the [Email API · Messages](/email-api/messages) reference. *** ## paubox schedule Manage scheduled emails: schedule, check status, reschedule, or cancel. ```bash theme={null} paubox schedule [options] ``` ### Subcommands | Subcommand | Description | | :- | :- | | `paubox schedule send [options]` | Schedule an email for future delivery | | `paubox schedule status ` | Check status of a scheduled email | | `paubox schedule reschedule --at ` | Change the scheduled time | | `paubox schedule cancel ` | Cancel a scheduled email | ### paubox schedule send Schedule an email for future delivery. ```bash theme={null} paubox schedule send --to --subject --at [options] ``` #### Flags | Flag | Required | Description | | :- | :- | :- | | `--to ` | Yes | Recipient email address. Repeat for multiple recipients | | `--subject ` | Yes | Email subject line | | `--at ` | Yes | Scheduled send time in ISO 8601 format (e.g. `2025-12-25T15:00:00Z`) | | `--html ` | One of `--html` or `--text` | HTML message body | | `--text ` | One of `--html` or `--text` | Plain-text message body | | `--from ` | No | Sender address. Defaults to `defaultFrom` from config if set | | `--attachment ` | No | Path to a file to attach. Repeat for multiple attachments | #### Example ```bash theme={null} paubox schedule send \ --to patient@example.com \ --from provider@yourclinic.com \ --subject "Appointment reminder" \ --text "Your appointment is tomorrow at 10am." \ --at 2025-12-25T15:00:00Z ``` #### Output ``` ✓ Email scheduled for 2025-12-25T15:00:00Z. Tracking ID: abc123-def456 ``` ### paubox schedule status Check the status of a scheduled email. ```bash theme={null} paubox schedule status ``` #### Example ```bash theme={null} paubox schedule status abc123-def456 ``` #### Output ``` ✓ Tracking ID: abc123-def456 State: pending Scheduled at: 2025-12-25T15:00:00Z ``` ### paubox schedule reschedule Change the scheduled delivery time of a pending email. ```bash theme={null} paubox schedule reschedule --at ``` #### Flags | Flag | Required | Description | | :- | :- | :- | | `--at ` | Yes | New scheduled send time in ISO 8601 format | #### Example ```bash theme={null} paubox schedule reschedule abc123-def456 --at 2025-12-26T10:00:00Z ``` #### Output ``` ✓ Email rescheduled to 2025-12-26T10:00:00Z. Tracking ID: abc123-def456 ``` ### paubox schedule cancel Cancel a scheduled email that has not yet been sent. ```bash theme={null} paubox schedule cancel ``` #### Example ```bash theme={null} paubox schedule cancel abc123-def456 ``` #### Output ``` ✓ Scheduled email cancelled. Tracking ID: abc123-def456 ``` *** ## paubox status Check the delivery status of a sent message. ```bash theme={null} paubox status ``` ### Example ```bash theme={null} paubox status abc123-def456 ``` ### Output ``` recipient status delivered at opened opened at ------------------- --------- ------------------------------- ------ ------------------------------- patient@example.com delivered Sun, 24 May 2026 09:14:02 -0700 opened Sun, 24 May 2026 09:17:45 -0700 ``` Times are shown as the API returns them. For a message that hasn't been opened, `opened` is empty and `opened at` shows `—`. > [!TIP] > > Add `--json` to get machine-readable output. Useful for parsing status in scripts and CI pipelines. The underlying API call is documented in the [Email API · Message receipt](/email-api/message-receipt) reference. *** ## paubox config Manage CLI configuration stored in `~/.config/paubox/config.json` (`%APPDATA%\paubox\config.json` on Windows). ```bash theme={null} paubox config ``` ### Subcommands | Subcommand | Description | | :- | :- | | `paubox config set ` | Set a configuration value | | `paubox config get ` | Print the current value for a key | | `paubox config list` | Print all configuration keys and values | | `paubox config reset` | Remove all configuration values | ### Supported keys | Key | Description | | :- | :- | | `defaultFrom` | Default sender address used when `--from` is not passed to `paubox send` | Additional keys may be added in future releases. ### Examples ```bash theme={null} # Set a default sender paubox config set defaultFrom provider@yourclinic.com # Confirm it was saved paubox config get defaultFrom # provider@yourclinic.com # List all config paubox config list # key value # ----------- ----------------------- # defaultFrom provider@yourclinic.com # Remove all config paubox config reset ``` > [!NOTE] > > `paubox config` stores general settings only. API credentials are managed separately with `paubox auth` and stored in the OS keychain. Without keychain support they are kept in the same `config.json` file, and `paubox config reset` leaves them in place. *** ## paubox receiving Manage receiving domains, mailboxes, and inbound email. ```bash theme={null} paubox receiving [options] ``` ### paubox receiving domains | Subcommand | Description | | :- | :- | | `paubox receiving domains list` | List all receiving domains | | `paubox receiving domains create [--slug SLUG]` | Create a receiving domain | | `paubox receiving domains get ` | Get a receiving domain | | `paubox receiving domains delete ` | Delete a receiving domain | #### Examples ```bash theme={null} # Create a domain with a custom slug paubox receiving domains create --slug support # List all domains paubox receiving domains list ``` ### paubox receiving mailboxes | Subcommand | Description | | :- | :- | | `paubox receiving mailboxes list ` | List mailboxes on a domain | | `paubox receiving mailboxes create --name NAME --password PASSWORD [--quota-bytes N]` | Create a mailbox | | `paubox receiving mailboxes get ` | Get a mailbox | | `paubox receiving mailboxes delete ` | Delete a mailbox | #### Examples ```bash theme={null} # Create a mailbox paubox receiving mailboxes create 1 --name intake --password SecurePass123! # List mailboxes on domain 1 paubox receiving mailboxes list 1 ``` ### paubox receiving emails | Subcommand | Description | | :- | :- | | `paubox receiving emails list [--limit N] [--after EMAIL_ID] [--before EMAIL_ID]` | List received emails | | `paubox receiving emails get ` | Get a received email | | `paubox receiving emails attachment [--output FILE] [--force]` | Download an attachment. `emailId` and `attachmentId` are UUIDs; `attachmentId` is the `id` of an entry in the email's attachments. Without `--output`, the file is named after the attachment. `--force` overwrites an existing file | #### Examples ```bash theme={null} # List the 10 most recent emails paubox receiving emails list --limit 10 # Get a specific email paubox receiving emails get 3f6c2a1e-8b4d-4c7a-9e2f-1a2b3c4d5e6f # Download an attachment paubox receiving emails attachment 3f6c2a1e-8b4d-4c7a-9e2f-1a2b3c4d5e6f 7d9e8f0a-1b2c-4d3e-8f4a-5b6c7d8e9f0a --output report.pdf ``` > [!TIP] > > Add `--json` to any receiving command for machine-readable output. The underlying API calls are documented in the [Email API · Receiving](/email-api/receiving) reference. *** ## paubox forms Fetch and submit Paubox Forms from the terminal, and manage forms, submissions, and Forms webhooks. `forms get` and `forms submit` call the public Forms endpoints and need no credentials. Every other `forms` command requires a Forms API key saved with `paubox auth set-forms-key`. ```bash theme={null} paubox forms [options] ``` ### Subcommands | Subcommand | Description | | :- | :- | | `paubox forms get ` | Fetch a form's metadata | | `paubox forms submit [options]` | Submit a response (and optional attachments) to a form | | `paubox forms list --customer-id [options]` | List forms. Filters: `--search`, `--form-id`, `--active `, `--archived `, `--order-by `, `--order `, `--page`, `--items` (default 50, max 100) | | `paubox forms stats [--customer-id ]` | Show form statistics. Defaults to the API key's customer | | `paubox forms submissions [options]` | List submissions. Options: `--submission-id`, `--order-by `, `--order `, `--page`, `--items` (default 50, max 100) | | `paubox forms export-csv [submissionId] [--output FILE] [--force]` | Export submissions as CSV | | `paubox forms export-pdf [--output FILE] [--force]` | Export one submission as PDF | | `paubox forms archive ` | Archive a form | | `paubox forms unarchive ` | Unarchive a form | | `paubox forms copy --title ` | Copy a form under a new title | | `paubox forms create --title <t> --customer-id <id> --form-json-file <path> [options]` | Create a form. Options: `--description`, `--recipient`, `--active`, `--signable`, `--signature-confirmation-label`, `--subscription-list-id`, `--type`, `--version` (default `1`), `--form-html-file`, `--form-css-file` | | `paubox forms update <formId> [options]` | Update a form; only the flags you pass are sent. Options: `--title`, `--description`, `--recipient`, `--active <true\|false>`, `--vanity-url`, `--subscription-list-id`, `--form-json-file` | | `paubox forms webhooks <subcommand>` | Manage Forms webhook subscriptions. See [paubox forms webhooks](#paubox-forms-webhooks) | ### paubox forms get Fetch a form's metadata, including its title, description, and submission count. ```bash theme={null} paubox forms get <formId> ``` #### Flags | Flag | Required | Description | | :- | :- | :- | | `<formId>` | Yes | UUID of the form to fetch | | `--json` | No | Return the raw API response object as JSON instead of the human-readable summary | #### Example ```bash theme={null} paubox forms get 550e8400-e29b-41d4-a716-446655440000 ``` #### Output ``` Form: Patient intake ID: 550e8400-e29b-41d4-a716-446655440000 Description: Initial visit questionnaire Active: true Submissions: 142 Signable: false Created: 2026-01-08T14:22:00Z Updated: 2026-05-19T09:41:00Z ``` > [!TIP] > > Add `--json` to get the raw API response object. Useful when you need the full Form payload, including `form_json`, `form_html`, and `form_css`, for rendering or validation. The underlying API call is documented in the [Forms · Get form metadata](/forms/get-form) reference. ### paubox forms submit Submit a response to a form, optionally with attachments. ```bash theme={null} paubox forms submit <formId> [options] ``` #### Flags | Flag | Required | Description | | :- | :- | :- | | `<formId>` | Yes | UUID of the form to submit a response to | | `--data <key>=<value>` | One of `--data` or `--data-file` | Form field as a `key=value` pair. Repeat for multiple fields. Values may contain `=` | | `--data-file <path>` | One of `--data` or `--data-file` | Path to a JSON file whose top-level string values are used as `form_data`. Merged with `--data`; `--data` takes precedence on key conflicts | | `--attach <file>` | No | File to include as an attachment. Repeat for multiple attachments. Total request size must not exceed 250 MB | | `--json` | No | Print machine-readable JSON output instead of the human-readable success line | #### Examples Submit with `--data` fields only: ```bash theme={null} paubox forms submit 550e8400-e29b-41d4-a716-446655440000 \ --data "first_name=Jane" \ --data "last_name=Doe" \ --data "email=jane@example.com" ``` Submit from a JSON file: ```bash theme={null} paubox forms submit 550e8400-e29b-41d4-a716-446655440000 --data-file ./fields.json ``` Override individual fields from a JSON file: ```bash theme={null} paubox forms submit 550e8400-e29b-41d4-a716-446655440000 \ --data-file ./base.json \ --data "field=override" ``` Submit with `--data` fields and an attachment: ```bash theme={null} paubox forms submit 550e8400-e29b-41d4-a716-446655440000 \ --data "name=Jane" \ --attach /path/to/signed-consent.pdf ``` #### Output ``` ✓ Form submitted successfully. ``` With `--json`: ```json theme={null} { "status": "ok", "formId": "550e8400-e29b-41d4-a716-446655440000" } ``` > [!TIP] > > Use `--json` when triggering submissions from CI pipelines or other automation that needs to confirm success programmatically. The underlying API call is documented in the [Forms · Submit form response](/forms/submit-form) reference. ### paubox forms webhooks Subscribe a URL to Forms events. Requires a Forms API key. | Subcommand | Description | | :- | :- | | `paubox forms webhooks list [--page N] [--items N]` | List subscriptions visible to your Forms API key (`--items` default 50, max 200) | | `paubox forms webhooks create --url <url> [--events <event...>]` | Subscribe a URL. The URL must be `https`. `--events` defaults to `forms.submission.created` | | `paubox forms webhooks get <subscriptionId>` | Show a subscription | | `paubox forms webhooks update <subscriptionId> [--url <url>] [--events <event...>] [--status <active\|disabled>]` | Update a subscription; only the flags you pass are sent. `--status disabled` pauses deliveries | | `paubox forms webhooks delete <subscriptionId>` | Delete a subscription | *** ## paubox webhooks Manage Email API webhook endpoints. Requires `paubox auth login`. | Subcommand | Description | | :- | :- | | `paubox webhooks list` | List webhook endpoints | | `paubox webhooks create --url <url> --events <event...> [--signing-key <key>] [--active\|--inactive]` | Create an endpoint. Endpoints are active unless you pass `--inactive` | | `paubox webhooks get <id>` | Get an endpoint | | `paubox webhooks update <id> [--url <url>] [--events <event...>] [--active\|--inactive]` | Update an endpoint; only the flags you pass are sent | | `paubox webhooks delete <id>` | Delete an endpoint | #### Example ```bash theme={null} paubox webhooks create \ --url https://example.com/paubox/webhooks \ --events api_mail_log_delivered api_mail_log_opened ``` See [Webhooks](/email-api/webhooks) for event types and payloads. *** ## Global options These flags work with any command. | Flag | Description | | :- | :- | | `--json` | Output results as JSON instead of human-readable text. Useful for scripting and CI pipelines | | `-q`, `--quiet` | Suppress all non-essential output. Errors are still printed | | `-v`, `--version` | Print the installed CLI version and exit | | `--help` | Print usage information for a command and exit | ### Examples ```bash theme={null} # Check version paubox --version # Get help for a specific command paubox send --help # Quiet mode: only print errors paubox send --to a@example.com --subject "Hi" --text "Hello" --quiet ``` ### Exit codes The CLI exits with `0` on success and a non-zero code on failure. Use this in scripts and CI pipelines to detect errors: ```bash theme={null} paubox send --to patient@example.com --subject "Hi" --text "Hello" || echo "Send failed" ``` # Paubox CLI Source: https://docs.paubox.com/cli/index Send HIPAA compliant email and drive Paubox Forms from the terminal using the Paubox CLI. The Paubox CLI is a command-line tool for the [Paubox Email API](/email-api) and [Paubox Forms](/forms). Use it to send and schedule encrypted email, check delivery status, manage inbound email and webhooks, work with forms, and manage configuration directly from your terminal or shell scripts, with no HTTP client required. ```bash theme={null} npm install -g paubox-cli ``` ## What you can do * Send encrypted, HIPAA compliant email with a single command * Schedule, reschedule, and cancel email for future delivery * Check delivery and open status for any sent message * Manage receiving domains and mailboxes, and read inbound email and attachments * Manage Email API webhook endpoints * Retrieve and submit Paubox Forms responses from the terminal * Manage Paubox Forms, export submissions, and subscribe to Forms webhooks with a Forms API key * Store API credentials securely in the OS keychain * Use `--json` output for scripting and automation * Set a default sender address so you don't repeat `--from` on every send ## Requirements * **Node.js** ≥ 20.12.0: [download at nodejs.org](https://nodejs.org) * **Linux only**: `libsecret-1-dev` is required for OS keychain support. Without it, credentials fall back to `~/.config/paubox/config.json` with `0600` permissions. ## Get started > [card] [Quickstart](/cli/quickstart) > > Install, authenticate, and send your first email in under five minutes. > [card] [Installation](/cli/installation) > > Full install guide for macOS, Windows, and Linux. > [card] [Authentication](/cli/authentication) > > Store and manage API credentials with the CLI. > [card] [Commands](/cli/commands) > > Full reference for every command and flag. ## Community & support > [card] [Q\&A](https://github.com/Paubox/community/discussions/categories/paubox-mcp-cli) > > Ask usage questions in the Paubox Community. > [card] [Ideas](https://github.com/Paubox/community/discussions/categories/ideas) > > Propose features and improvements. > [!WARNING] > > Never post PHI, recipient addresses, or message content in public threads. Account, billing, or anything sensitive goes to [support@paubox.com](mailto:support@paubox.com). # Installation Source: https://docs.paubox.com/cli/installation Install the Paubox CLI with npm or Homebrew on macOS, then verify the install and enable keychain support on Linux. ## Requirements * **Node.js** ≥ 20.12.0. Download at [nodejs.org](https://nodejs.org) or install via your preferred version manager (`nvm`, `fnm`, etc.). * **Linux only**: Install `libsecret-1-dev` before running the CLI if you want OS keychain support. See [Linux: keychain support](#linux-keychain-support) below. ## Install ```bash npm (all platforms) theme={null} npm install -g paubox-cli ``` ```bash Homebrew (macOS) theme={null} brew tap paubox/paubox brew install paubox-cli ``` ## Verify the installation ```bash theme={null} paubox --version ``` You should see output like `1.4.0`. If the command is not found, ensure your global npm bin directory is on your `PATH`. ## Linux: keychain support The Paubox CLI stores credentials in the OS keychain by default. On Linux, this requires the Secret Service API, which is provided by GNOME Keyring or KWallet. The underlying `keytar` library needs `libsecret-1-dev` at install time. On Debian/Ubuntu: ```bash theme={null} sudo apt install libsecret-1-dev npm install -g paubox-cli ``` On Fedora/RHEL: ```bash theme={null} sudo dnf install libsecret-devel npm install -g paubox-cli ``` **Fallback behavior:** If `libsecret` is not available, credentials are stored in `~/.config/paubox/config.json` with `0600` permissions (readable only by your user). `paubox auth login` and `paubox auth status` report where credentials are stored (`OS keychain` or `config file`). > [!WARNING] > > If you share a machine or use file-based credential storage, ensure `~/.config/paubox/config.json` is excluded from any backups or source control. # Paubox CLI quickstart Source: https://docs.paubox.com/cli/quickstart Install the Paubox CLI, authenticate, and send your first email in under five minutes. **1. Install the CLI** Install the Paubox CLI globally with npm: ```bash theme={null} npm install -g paubox-cli ``` Verify the install: ```bash theme={null} paubox --version ``` For the Homebrew (macOS) install option, see [Installation](/cli/installation). **2. Authenticate** Run `auth login` and enter your Paubox API key when prompted: ```bash theme={null} paubox auth login ``` ``` ✔ API key: ******************************** Validating credentials… ✓ Authenticated (API key: ****abcd, stored in OS keychain) ``` Your API key is stored securely in your OS keychain. To get your API key, see [Authentication](/cli/authentication). **3. Send an email** Send your first encrypted email: ```bash theme={null} paubox send \ --to patient@example.com \ --from provider@yourclinic.com \ --subject "Your appointment summary" \ --html "<p>Thank you for visiting us today.</p>" ``` On success, the CLI prints a tracking ID: ``` ✓ Email sent. Tracking ID: abc123-def456 ``` **4. Check delivery status** Pass the tracking ID to `paubox status`: ```bash theme={null} paubox status abc123-def456 ``` ``` recipient status delivered at opened opened at ------------------- --------- ------------------------------- ------ ------------------------------- patient@example.com delivered Sun, 24 May 2026 09:14:02 -0700 opened Sun, 24 May 2026 09:17:45 -0700 ``` ## Next steps * [Installation](/cli/installation): install on other platforms or verify system requirements * [Commands](/cli/commands): full reference for every command and global option # C# SDK authentication Source: https://docs.paubox.com/csharp-sdk/authentication Configure Paubox API credentials for the C# SDK with a constructor parameter or IConfiguration in ASP.NET Core, plus Forms client setup and security notes. ## Obtain your API key The Email API client requires a single credential: * **API key**: a secret token that authenticates your requests It is available in the [Paubox dashboard](https://next.paubox.com) under **API Credentials**. ## Option 1: Constructor parameter Pass your API key directly; useful for console apps or when managing secrets via environment variables: ```csharp theme={null} var emailLib = new EmailLibrary("YOUR_API_KEY"); ``` Read from an environment variable: ```csharp theme={null} var emailLib = new EmailLibrary( Environment.GetEnvironmentVariable("PAUBOX_API_KEY") ); ``` ## Option 2: IConfiguration (recommended for ASP.NET Core) Add your API key to `appsettings.json`: ```json theme={null} { "APIKey": "YOUR_API_KEY" } ``` Then inject `IConfiguration` and pass it to the constructor: ```csharp theme={null} // In Program.cs or Startup.cs builder.Services.AddSingleton<IEmailLibrary>(sp => { var config = sp.GetRequiredService<IConfiguration>(); return new EmailLibrary(config); }); ``` Or instantiate directly: ```csharp theme={null} var emailLib = new EmailLibrary(configuration); ``` The SDK reads `APIKey` from the configuration and sets the `Authorization` header automatically on every request: ``` Authorization: Token token=YOUR_API_KEY ``` ## Forms client `GetForm` and `SubmitForm` are public and need no credentials: ```csharp theme={null} var formsLib = new FormsLibrary(); ``` All other Forms methods need an API key with the `forms` scope, sent as `Authorization: Bearer YOUR_API_KEY`. Pass it to the constructor, or set `FormsAPIKey` (and optionally `FormsBaseURL`) in configuration: ```csharp theme={null} var formsLib = new FormsLibrary("YOUR_API_KEY"); // Or read FormsAPIKey from IConfiguration var configuredFormsLib = new FormsLibrary(configuration); ``` Use `IFormsLibrary` in ASP.NET Core for dependency injection and testability: ```csharp theme={null} builder.Services.AddSingleton<IFormsLibrary, FormsLibrary>(); ``` ## Receiving and webhook clients `ReceivingLibrary` takes the same API key as `EmailLibrary`, either as a constructor argument or from `APIKey` in configuration. `WebhookLibrary` needs a scoped API key, sent as `Authorization: Bearer YOUR_API_KEY`. Pass it to the constructor, or set `WebhooksAPIKey` (and optionally `WebhooksBaseURL`) in configuration. See [Webhook client](/csharp-sdk/webhook-client). ## Security notes * Never hard-code credentials in source files. Use `appsettings.json` with user secrets or environment variables. * Use [.NET user secrets](https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets) during development to keep credentials out of source control. # C# SDK email client Source: https://docs.paubox.com/csharp-sdk/email-client Full reference for the Paubox C# SDK Email API client: sending messages, bulk sending, delivery tracking, dynamic templates, and error handling. ## Instantiation ```csharp theme={null} // Direct API key var emailLib = new EmailLibrary("YOUR_API_KEY"); // IConfiguration (ASP.NET Core) var emailLib = new EmailLibrary(configuration); ``` See [Authentication](/csharp-sdk/authentication) for both approaches. Use `IEmailLibrary` for dependency injection. ## Building a message ```csharp theme={null} var message = new Message { Recipients = new[] { "alice@example.com" }, // required Cc = new[] { "manager@example.com" }, // optional Bcc = new[] { "audit@example.com" }, // optional Header = new Header { From = "sender@yourdomain.com", // required Subject = "Your results are ready", // required ReplyTo = "support@yourdomain.com", // optional CustomHeaders = new Dictionary<string, string> // optional { { "X-Custom-Header", "value" } } }, Content = new Content { PlainText = "Plain text body.", // at least one required HtmlText = "<p>HTML body.</p>" // optional; auto base64-encoded }, Attachments = new List<Attachment> { attachment }, // optional AllowNonTLS = false, // optional; default false ForceSecureNotification = "true" // optional; "true" or "false" }; ``` ### Attachments ```csharp theme={null} byte[] fileBytes = File.ReadAllBytes("report.pdf"); var attachment = new Attachment { FileName = "report.pdf", ContentType = "application/pdf", Content = Convert.ToBase64String(fileBytes) }; message.Attachments = new List<Attachment> { attachment }; ``` ## Send a message ```csharp theme={null} SendMessageResponse response = emailLib.SendMessage(message); Console.WriteLine("Tracking ID: " + response.SourceTrackingId); ``` The `SendMessageResponse` includes: | Property | Description | | - | - | | `SourceTrackingId` | Use to check delivery status | | `Data` | Raw response data | | `Errors` | List of `Error` objects if the request failed | ## Send bulk messages Send up to 50 messages in a single API call. Each message gets its own tracking ID. ```csharp theme={null} var messages = new[] { new Message { Recipients = new[] { "alice@example.com" }, Header = new Header { From = "f@yourdomain.com", Subject = "Hi Alice" }, Content = new Content { PlainText = "Hello Alice" } }, new Message { Recipients = new[] { "bob@example.com" }, Header = new Header { From = "f@yourdomain.com", Subject = "Hi Bob" }, Content = new Content { PlainText = "Hello Bob" } } }; SendBulkMessagesResponse bulkResponse = emailLib.SendBulkMessages(messages); foreach (var msg in bulkResponse.Messages) { Console.WriteLine($"Tracking ID: {msg.SourceTrackingId}"); } ``` ## Check delivery status ```csharp theme={null} GetEmailDispositionResponse disposition = emailLib.GetEmailDisposition(response.SourceTrackingId); foreach (var delivery in disposition.Data.Message.Message_Deliveries) { Console.WriteLine($"{delivery.Recipient} → {delivery.Status.DeliveryStatus}"); } ``` Common `DeliveryStatus` values: `delivered`, `delivered via secure portal`, `soft bounced`, `hard bounced`, `processing`. Opens are reported separately in `OpenedStatus`, which is `"unopened"` until the message is opened. ## Scheduled send Schedule a message for future delivery, check its status, reschedule, or cancel it. ### Schedule a message ```csharp theme={null} string scheduledAt = DateTime.UtcNow.AddDays(1).ToString("o"); ScheduleMessageResponse response = emailLib.ScheduleMessage(message, scheduledAt); Console.WriteLine("Tracking ID: " + response.SourceTrackingId); Console.WriteLine("Scheduled for: " + response.ScheduledAt); ``` `scheduledAt` must be an ISO 8601 UTC datetime string in the future and within 30 days. ### Get scheduled message status ```csharp theme={null} ScheduledMessageStatusResponse status = emailLib.GetScheduledMessage(sourceTrackingId); Console.WriteLine($"State: {status.State}"); // "pending", "processing", "sent", "failed", "cancelled" Console.WriteLine($"Scheduled for: {status.ScheduledAt}"); ``` ### Reschedule a message ```csharp theme={null} string newTime = DateTime.UtcNow.AddDays(2).ToString("o"); RescheduleResponse response = emailLib.RescheduleMessage(sourceTrackingId, newTime); Console.WriteLine("New time: " + response.ScheduledAt); ``` ### Cancel a scheduled message ```csharp theme={null} CancelScheduledResponse response = emailLib.CancelScheduledMessage(sourceTrackingId); Console.WriteLine("State: " + response.State); // "cancelled" ``` ## Dynamic templates Templates use [Handlebars](https://handlebarsjs.com) syntax (`{{variable_name}}`). ### Create a template ```csharp theme={null} DynamicTemplateResponse created = emailLib.CreateDynamicTemplate( templateName: "appointment-confirmation", templatePath: @"C:\templates\appointment.html" ); ``` The API responds with the template itself, which doesn't match `DynamicTemplateResponse`, so in SDK v1.3.1 through v2.0.0 the returned object's properties are `null` even though the template was created. The same applies to `UpdateDynamicTemplate`. ### List templates ```csharp theme={null} List<DynamicTemplateSummary> templates = emailLib.ListDynamicTemplates(); ``` In SDK v1.3.1 through v2.0.0, `ListDynamicTemplates` expects a JSON array, but the API returns an object with a `templates` array, so the call throws `JsonSerializationException`. The [List dynamic templates](/email-api/dynamic-templates) API reference shows the response. ### Get a template ```csharp theme={null} GetDynamicTemplateResponse tmpl = emailLib.GetDynamicTemplate(templateId); ``` ### Update a template ```csharp theme={null} DynamicTemplateResponse updated = emailLib.UpdateDynamicTemplate( templateId: 123, templateName: "appointment-confirmation-v2", templatePath: @"C:\templates\appointment-v2.html" ); ``` ### Delete a template ```csharp theme={null} DeleteDynamicTemplateResponse deleted = emailLib.DeleteDynamicTemplate(templateId); ``` ### Send a templated message ```csharp theme={null} var templatedMsg = new TemplatedMessage { Recipients = new[] { "jane@example.com" }, Header = new Header { From = "appointments@yourclinic.com", Subject = "Your appointment" }, TemplateName = "appointment-confirmation", TemplateValues = new Dictionary<string, object> { { "first_name", "Jane" }, { "date", "2024-03-15" }, { "time", "2:00 PM" } } }; SendMessageResponse response = emailLib.SendTemplatedMessage(templatedMsg); ``` ## Error handling A non-2xx HTTP response throws `PauboxApiException`, which exposes `StatusCode` and the raw response `Body`. A 2xx response whose body contains API errors throws `SystemException` with the raw JSON response as its message: ```csharp theme={null} try { SendMessageResponse response = emailLib.SendMessage(message); } catch (PauboxApiException ex) { // ex.Body holds the raw response body Console.WriteLine("API error: " + ex.StatusCode); } catch (SystemException ex) { // ex.Message contains the raw JSON error response Console.WriteLine("API error: " + ex.Message); } ``` # C# SDK forms client Source: https://docs.paubox.com/csharp-sdk/forms-client Retrieve Paubox Form schemas and submit form responses using the C# SDK. `GetForm` and `SubmitForm` do not require API credentials. The form management methods require an API key with the `forms` scope (see [Manage forms](#manage-forms)). Forms are identified by a UUID that you obtain from the Paubox dashboard. ## Instantiation ```csharp theme={null} var formsLib = new FormsLibrary(); ``` Use `IFormsLibrary` for dependency injection in ASP.NET Core: ```csharp theme={null} builder.Services.AddSingleton<IFormsLibrary, FormsLibrary>(); ``` ## Get a form Retrieve a form's metadata, field schema, and rendered HTML/CSS: ```csharp theme={null} Form form = formsLib.GetForm("your-form-uuid"); Console.WriteLine("Title: " + form.Title); Console.WriteLine("HTML: " + form.FormHtml); ``` The `Form` object includes: | Property | Description | | - | - | | `Title` | Display name of the form | | `FormJson` | Parsed field schema | | `FormHtml` | Rendered HTML for embedding | | `FormCss` | Associated stylesheet | | `Active` | Whether the form is accepting submissions | | `SubmissionCount` | Number of submissions received | | `CreatedAt` / `UpdatedAt` | Timestamps | ## Submit a form ```csharp theme={null} var formData = new Dictionary<string, object> { { "first_name", "Jane" }, { "last_name", "Smith" }, { "email", "jane@example.com" } }; formsLib.SubmitForm("your-form-uuid", formData); ``` `SubmitForm` returns `void` on success and throws on failure. ### Submitting with file attachments The maximum total request size is 250 MB. ```csharp theme={null} byte[] fileBytes = File.ReadAllBytes("consent.pdf"); var attachments = new[] { new FormAttachment { Name = "consent.pdf", Content = Convert.ToBase64String(fileBytes) } }; formsLib.SubmitForm("your-form-uuid", formData, attachments); ``` The `FormAttachment` properties: | Property | Description | | - | - | | `Name` | File name including extension | | `Content` | Base64-encoded file content | ## Manage forms These methods require a `FormsLibrary` constructed with an API key that has the `forms` scope, either `new FormsLibrary("YOUR_API_KEY")` or `new FormsLibrary(configuration)` with `FormsAPIKey` set. The key is sent as `Authorization: Bearer YOUR_API_KEY`. Without a key they throw `InvalidOperationException`. | Method | Returns | | - | - | | `ListForms(FormsListParams)` | `FormsListResponse`; `CustomerId` is required | | `CreateForm(CreateFormRequest)` | `CreateFormResponse` | | `GetFormById(formId)` | `Form` | | `UpdateForm(formId, UpdateFormRequest)` | `UpdateFormResponse` | | `ArchiveForm(formId)` / `UnarchiveForm(formId)` | `string` detail message | | `CopyForm(formId, newTitle)` | `Form` | | `GetFormStats(customerId)` | `FormStats`; `customerId` is optional | | `ListFormSubmissions(formId, SubmissionListParams)` | `FormSubmissionListResponse` | | `ExportSubmissionsCsv(formId)` | `string` CSV | | `ExportSubmissionCsv(formId, submissionId)` | `string` CSV | | `ExportSubmissionPdf(formId, submissionId)` | `byte[]` PDF | ```csharp theme={null} var formsAdmin = new FormsLibrary("YOUR_API_KEY"); FormsListResponse list = formsAdmin.ListForms(new FormsListParams { CustomerId = 12345, Active = true, Page = 1, Items = 25 }); foreach (Form f in list.Results) Console.WriteLine($"{f.Id}: {f.Title}"); ``` ## Error handling Non-2xx responses throw `PauboxApiException`. Its `Message` contains only the verb, endpoint, and status; the raw response body is on `Body`. ```csharp theme={null} try { Form form = formsLib.GetForm("your-form-uuid"); formsLib.SubmitForm("your-form-uuid", formData); } catch (ArgumentException ex) { // Null, empty, or non-UUID formId, or null formData Console.WriteLine("Invalid argument: " + ex.Message); } catch (PauboxApiException ex) { // API error (404 form not found, 400 bad request, etc.) Console.WriteLine($"API error {ex.StatusCode}: {ex.Message}"); } ``` # Paubox C# SDK Source: https://docs.paubox.com/csharp-sdk/index Send HIPAA compliant email and submit Paubox Forms from .NET applications using the official Paubox C# SDK. The Paubox C# SDK is the official .NET client library for the [Paubox Email API](/email-api) and [Paubox Forms](/forms). It provides a strongly-typed interface for sending encrypted email, managing dynamic templates, tracking delivery, and submitting forms. ## Installation The SDK is not published to NuGet. The `lib/Paubox.Email.API.dll` committed to the repository dates from 2019 and only supports sending a message and checking its disposition, so do not reference it. Instead, either reference the SDK project from a clone of the repository, or download the `Paubox.Email.API-<version>.dll` asset from the [latest GitHub release](https://github.com/Paubox/paubox-csharp/releases/latest). **Project reference (recommended):** ```bash theme={null} git clone https://github.com/Paubox/paubox-csharp.git ``` ```xml theme={null} <ItemGroup> <ProjectReference Include="path\to\paubox-csharp\Paubox_Csharp\EmailLib\EmailLib.csproj" /> </ItemGroup> ``` **DLL reference:** build the DLL yourself with `dotnet build Paubox_Csharp/EmailLib/EmailLib.csproj --configuration Release` (output: `Paubox_Csharp/EmailLib/bin/Release/net8.0/Paubox.Email.API.dll`) or use the release asset, then reference it and add the packages it depends on: ```xml theme={null} <ItemGroup> <Reference Include="Paubox.Email.API"> <HintPath>path\to\Paubox.Email.API.dll</HintPath> </Reference> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" /> </ItemGroup> ``` ## What you can do * Send encrypted, HIPAA compliant email to one or more recipients * Send batches of up to 50 messages in a single API call * Create, update, and delete dynamic Handlebars templates * Send templated messages with per-message variable substitution * Track delivery status and engagement per recipient * Schedule, reschedule, and cancel messages * Retrieve Paubox Form schemas and submit form responses with file attachments * Manage forms, submissions, and exports with a forms-scoped API key * Manage receiving domains and mailboxes, and read inbound email * Manage webhook endpoints ## Requirements * .NET 8.0 or later (.NET 9.0 also supported) ## Dependency injection The SDK ships with `IEmailLibrary`, `IFormsLibrary`, `IReceivingLibrary`, and `IWebhookLibrary` interfaces, making it straightforward to register the clients in an ASP.NET Core DI container and mock them in tests. ## Get started > [card] [Quickstart](/csharp-sdk/quickstart) > > Add the SDK, configure credentials, and send your first email in minutes. > [card] [Authentication](/csharp-sdk/authentication) > > Configure via constructor params or appsettings.json. > [card] [Email client](/csharp-sdk/email-client) > > Full reference for sending email, managing templates, and tracking delivery. > [card] [Forms client](/csharp-sdk/forms-client) > > Retrieve form schemas and submit responses. > [card] [Receiving client](/csharp-sdk/receiving-client) > > Manage receiving domains and mailboxes, and read inbound email. > [card] [Webhook client](/csharp-sdk/webhook-client) > > Create and manage webhook endpoints. # C# SDK quickstart Source: https://docs.paubox.com/csharp-sdk/quickstart Add the Paubox C# SDK and send your first HIPAA compliant email in minutes. **1. Add the SDK** The SDK is not on NuGet, and the `lib/Paubox.Email.API.dll` committed to the repository is a 2019 build that lacks most of this API. Clone the repository and reference the SDK project: ```bash theme={null} git clone https://github.com/Paubox/paubox-csharp.git ``` ```xml theme={null} <ItemGroup> <ProjectReference Include="path\to\paubox-csharp\Paubox_Csharp\EmailLib\EmailLib.csproj" /> </ItemGroup> ``` To reference a DLL instead, see [Installation](/csharp-sdk#installation). **2. Instantiate the client** Pass your API key directly to the constructor: ```csharp theme={null} using Paubox; var emailLib = new EmailLibrary("YOUR_API_KEY"); ``` For ASP.NET Core applications, see [Authentication](/csharp-sdk/authentication) for the `IConfiguration` approach. **3. Send your first email** ```csharp theme={null} var message = new Message { Recipients = new[] { "recipient@example.com" }, Header = new Header { From = "sender@yourdomain.com", Subject = "Your first Paubox email" }, Content = new Content { PlainText = "This message was sent with the Paubox C# SDK." } }; SendMessageResponse response = emailLib.SendMessage(message); Console.WriteLine("Sent. Tracking ID: " + response.SourceTrackingId); ``` **4. Check delivery status** ```csharp theme={null} GetEmailDispositionResponse disposition = emailLib.GetEmailDisposition(response.SourceTrackingId); foreach (var delivery in disposition.Data.Message.Message_Deliveries) { Console.WriteLine($"{delivery.Recipient} → {delivery.Status.DeliveryStatus}"); } ``` ## Next steps * [Email client](/csharp-sdk/email-client): bulk send, attachments, dynamic templates, error handling * [Forms client](/csharp-sdk/forms-client): retrieve form schemas and submit responses # C# SDK receiving client Source: https://docs.paubox.com/csharp-sdk/receiving-client Full reference for the Paubox C# SDK receiving API: managing domains, mailboxes, and retrieving inbound email. Receiving endpoints are exposed through the `ReceivingLibrary` class, which uses the same `Token token=` authentication as `EmailLibrary`. ```csharp theme={null} var receiving = new ReceivingLibrary("YOUR_API_KEY"); ``` Or with `IConfiguration`: ```csharp theme={null} var receiving = new ReceivingLibrary(configuration); ``` ## Domains ### List domains ```csharp theme={null} ReceivingDomainListResponse domains = receiving.ListReceivingDomains(); foreach (var d in domains.Data) Console.WriteLine($"{d.Id}: {d.Domain}"); ``` The API reports a domain's status in `status` and `state`, which `ReceivingDomain` in SDK v1.3.1 through v2.0.0 doesn't map. Its `Verified` property is always `false`, and `Slug` and `DnsRecords` are always `null`. ### Create a domain ```csharp theme={null} ReceivingDomainResponse created = receiving.CreateReceivingDomain("support"); ``` Omit the slug or pass `null` to auto-generate one. ### Get a domain ```csharp theme={null} ReceivingDomainResponse domain = receiving.GetReceivingDomain(1); ``` ### Delete a domain ```csharp theme={null} DeleteReceivingDomainResponse deleted = receiving.DeleteReceivingDomain(1); ``` ## Mailboxes ### List mailboxes ```csharp theme={null} MailboxListResponse mailboxes = receiving.ListMailboxes(domainId); ``` ### Create a mailbox ```csharp theme={null} MailboxResponse mailbox = receiving.CreateMailbox(domainId, new CreateMailboxRequest { Name = "intake", Password = "YOUR_MAILBOX_PASSWORD", QuotaBytes = 1073741824 // optional }); ``` ### Get a mailbox ```csharp theme={null} MailboxResponse mailbox = receiving.GetMailbox(domainId, mailboxId); ``` ### Delete a mailbox ```csharp theme={null} DeleteMailboxResponse deleted = receiving.DeleteMailbox(domainId, mailboxId); ``` ## Emails ### List received emails ```csharp theme={null} ReceivedEmailListResponse emails = receiving.ListReceivedEmails(new ListReceivedEmailsParams { Limit = 10 }); foreach (var e in emails.Data) Console.WriteLine($"{e.Id}: {e.Subject}"); ``` `ListReceivedEmailsParams` also accepts `After` and `Before` cursors for pagination; `HasMore` on the response indicates whether more results exist. ### Get a received email ```csharp theme={null} ReceivedEmail email = receiving.GetReceivedEmail(emailId).Data; ``` ### Download an attachment Pass the attachment's `Id` from `ReceivedEmail.Attachments`. The content is returned as bytes: ```csharp theme={null} ReceivedAttachment attachment = email.Attachments[0]; byte[] content = receiving.DownloadAttachmentBytes(email.Id, attachment.Id); File.WriteAllBytes(Path.GetFileName(attachment.Filename), content); ``` `DownloadAttachment` is obsolete: it returns the content as a string, which corrupts binary files. # C# SDK webhook client Source: https://docs.paubox.com/csharp-sdk/webhook-client Create, list, get, update, and delete Paubox webhook endpoints with the C# SDK to receive Email API and Forms events. > [!NOTE] > > The methods on this page require SDK 2.0.0 or later, where `WebhookLibrary` uses the Paubox webhooks service and a scoped API key. `WebhookLibrary`, which implements `IWebhookLibrary`, manages webhook endpoints through the Paubox webhooks service at `https://api.paubox.com/v1/webhooks`. It sends a scoped API key as `Authorization: Bearer YOUR_API_KEY`. The key's scopes decide which events it can subscribe to. ## Create the client ```csharp theme={null} using Paubox; var webhooks = new WebhookLibrary("YOUR_API_KEY"); ``` To read the key from `IConfiguration`, use `new WebhookLibrary(configuration)`. It reads `WebhooksAPIKey` and, optionally, `WebhooksBaseURL`, and throws `ArgumentException` if `WebhooksAPIKey` is missing. It doesn't use `APIKey`. ## Events | Event | Required scope | Fires when | | - | - | - | | `api_mail_log_delivered` | `email_api` | An Email API message is delivered | | `api_mail_log_opened` | `email_api` | A delivered message is opened | | `api_mail_log_temporary_failure` | `email_api` | Delivery fails temporarily | | `api_mail_log_permanent_failure` | `email_api` | Delivery fails permanently | | `email.inbound.received` | `email_api`, with no sender-domain limit | Inbound mail is received | | `forms.submission.created` | `forms` | A form submission is received | The SDK doesn't check event names. The API returns 422 for an unknown event and 403 for an event the key isn't scoped for. Email API keys created in the Paubox Dashboard are limited to a sender domain, so subscribe to inbound mail in the Paubox Dashboard under [Settings > Webhooks](https://next.paubox.com/settings/webhooks). For payloads and signature verification, see [Webhooks](/email-api/webhooks). ## List webhook endpoints ```csharp theme={null} WebhookEndpointList result = webhooks.ListWebhookEndpoints(new ListWebhookEndpointsParams { Page = 1, Items = 50, }); foreach (WebhookEndpoint endpoint in result.Data) { Console.WriteLine($"{endpoint.Id} {endpoint.TargetUrl} {endpoint.Status}"); } Console.WriteLine(result.PageInfo.Count); ``` The argument is optional. `PageInfo.Count` is the total number of endpoints, not the length of `Data`. Endpoints carrying an event the key isn't scoped for are left out. ## Create a webhook endpoint ```csharp theme={null} CreatedWebhookEndpoint created = webhooks.CreateWebhookEndpoint(new CreateWebhookEndpointRequest { TargetUrl = "https://example.com/webhooks/paubox", Events = new List<string> { "api_mail_log_delivered", "api_mail_log_opened" }, }); Console.WriteLine(created.Id); Console.WriteLine(created.SigningSecret); ``` `TargetUrl` must be an `https` URL that doesn't point at a private or internal address. `WebhookEndpoint` has `Id` (a UUID), `TargetUrl`, `Status` (`active` or `disabled`), `Events`, `CreatedAt`, and `UpdatedAt`. `CreatedWebhookEndpoint` extends it with `SigningSecret`, which is returned only by this call; store it when you create the endpoint. To replace a lost secret, delete the endpoint and create a new one. ## Get a webhook endpoint ```csharp theme={null} WebhookEndpoint endpoint = webhooks.GetWebhookEndpoint("2ec66c21-bf48-48eb-8d28-f80b2d6b77c7"); ``` ## Update a webhook endpoint ```csharp theme={null} WebhookEndpoint updated = webhooks.UpdateWebhookEndpoint( "2ec66c21-bf48-48eb-8d28-f80b2d6b77c7", new UpdateWebhookEndpointRequest { Status = "disabled" }); ``` `UpdateWebhookEndpointRequest` has optional `TargetUrl`, `Status` (`"active"` or `"disabled"`), and `Events` properties. Only the properties you set are sent. `Events` replaces the endpoint's event list. ## Delete a webhook endpoint ```csharp theme={null} webhooks.DeleteWebhookEndpoint("2ec66c21-bf48-48eb-8d28-f80b2d6b77c7"); ``` ## Error handling ```csharp theme={null} try { webhooks.CreateWebhookEndpoint(new CreateWebhookEndpointRequest { TargetUrl = "https://example.com/webhooks/paubox", Events = new List<string> { "api_mail_log_delivered" }, }); } catch (PauboxApiException ex) { Console.WriteLine(ex.StatusCode); Console.WriteLine(ex.Body); } ``` A non-2xx response throws `PauboxApiException`, which provides `StatusCode`, `Verb`, `Endpoint`, and `Body` (the raw response, including the API's `message`). Creating a second endpoint for the same `TargetUrl` returns 422, and an ID that isn't on your account returns 404. An ID that isn't a UUID throws `ArgumentException` before any request is sent. # General information Source: https://docs.paubox.com/email-api Base URL, authentication, date formats, and response codes for the Paubox Email API. If you're not sure where to start, visit the [Quickstart guide](/email-api/quickstart). To set up credentials, see [Authentication](/email-api/authentication). ## Base URL `https://api.paubox.com/v1/email` ## Authorization Pass your API key as a Bearer token in every request: `Authorization: Bearer YOUR_API_KEY` The legacy format `Authorization: Token token=YOUR_API_KEY` is also accepted. Bearer is preferred. ## Date format Request dates, such as `scheduled_at` when [scheduling an email](/email-api/scheduled-send/schedule), are ISO 8601 (RFC 3339) strings with a time zone, e.g. `"2027-12-25T15:00:00Z"`. Timestamps in scheduled send, dynamic template, and webhook endpoint responses use the same format. The [message receipt](/email-api/message-receipt) is different: its `deliveryTime` and `openedTime` values are RFC 2822 strings, e.g. `"Mon, 23 Apr 2018 20:27:34 +0000"`. ## Standard HTTP response codes | **Status Code** | **Status Message** | | :- | :- | | 200 | Service Ok | | 400 | Bad Request | | 401 | Unauthorized | | 403 | Forbidden (including new accounts during the 24-hour review after signup) | | 404 | Not Found | | 422 | Unprocessable Entity | | 500, 502, 503, 504 | Server Error | See [Errors](/email-api/errors) for causes and the error response format. ## Community & support > [card] [Q\&A](https://github.com/Paubox/community/discussions/categories/paubox-email-api) > > Ask usage questions in the Paubox Community. > [card] [Ideas](https://github.com/Paubox/community/discussions/categories/ideas) > > Propose features and improvements. > [!WARNING] > > Never post PHI, recipient addresses, or message content in public threads. Account, billing, or anything sensitive goes to [support@paubox.com](mailto:support@paubox.com). # Attachments Source: https://docs.paubox.com/email-api/attachments Attach files to emails sent with the Paubox Email API: attachment fields and Base64 content, with REST API, SDK, and CLI examples. You can attach files to any message sent through the Email API. Attachments are added as an `attachments` array on the message, where each entry describes a single file. > [!NOTE] > > The whole request body, including Base64-encoded attachments, must not exceed **50 MB**. Base64 adds about a third to file size, so plan for roughly 37 MB of raw files per message. See [Limits and overage rates](/email-api/limits) for all sending limits. ## Attachment fields Each attachment is an object with three required fields and two optional ones: | Field | Type | Description | | :- | :- | :- | | `fileName` | string | Name the recipient will see, including the extension (e.g. `report.pdf`). | | `contentType` | string | Valid MIME type for the file, e.g. `application/pdf` or `text/plain`. | | `content` | string | The file contents, Base64-encoded. | | `disposition` | string | Optional. `attachment` (default) or `inline`. | | `contentId` | string | Required when `disposition` is `inline`. The ID you reference from your HTML. | ## REST API example Add the `attachments` array to the message body. The example below attaches a small text file (`Hello World!` Base64-encoded as `SGVsbG8gV29ybGQh`): ```json theme={null} { "data": { "message": { "recipients": ["recipient@host.com"], "headers": { "subject": "Sample email with an attachment", "from": "sender@verifieddomain.com" }, "content": { "text/plain": "Hello World!" }, "attachments": [ { "fileName": "hello_world.txt", "contentType": "text/plain", "content": "SGVsbG8gV29ybGQh" } ] } } } ``` See the full [Send a message](/email-api/messages) reference for the complete request body. ## Inline images To embed an image in the HTML body, set `disposition` to `inline`, give it a `contentId`, and reference that ID with a `cid:` URL. Inline attachments must use an `image/*` `contentType`; otherwise the request returns `400`. ```json theme={null} { "data": { "message": { "recipients": ["recipient@host.com"], "headers": { "subject": "Sample email with an inline image", "from": "sender@verifieddomain.com" }, "content": { "text/html": "<html><body><img src=\"cid:logo\"></body></html>" }, "attachments": [ { "fileName": "logo.png", "contentType": "image/png", "content": "BASE64_ENCODED_IMAGE", "disposition": "inline", "contentId": "logo" } ] } } } ``` ## SDK examples Most Paubox SDKs accept attachments in the same `fileName` / `contentType` / `content` shape. The file content is always Base64-encoded. ```python Python theme={null} import base64 with open('report.pdf', 'rb') as f: encoded = base64.b64encode(f.read()).decode('utf-8') attachment = { 'fileName': 'report.pdf', 'contentType': 'application/pdf', 'content': encoded } # Pass attachments via the optional_headers dict optional_headers = { 'attachments': [attachment] } ``` ```javascript Node.js theme={null} const fs = require('fs'); const attachment = { fileName: 'report.pdf', contentType: 'application/pdf', content: fs.readFileSync('report.pdf').toString('base64') }; const options = { attachments: [attachment] }; ``` For language-specific details, see each SDK's email client guide — for example the [Python SDK](/python-sdk/email-client) or [Node.js SDK](/node-sdk/email-client). ## Sending from the CLI The Paubox CLI accepts files directly with the `--attachment` flag and handles the Base64 encoding for you: ```bash theme={null} paubox send \ --from sender@verifieddomain.com \ --to recipient@host.com \ --subject "Sample email with an attachment" \ --text "Hello World!" \ --attachment report.pdf ``` See the [CLI commands reference](/cli/commands) for all available flags. # Email API authentication Source: https://docs.paubox.com/email-api/authentication Find your Paubox Email API key and pass it in requests with the Bearer or legacy Token authorization header, plus best practices for key rotation. Every request to the Paubox Email API must include your API key in the `Authorization` header. Keys are managed from the [Settings > API Keys](https://next.paubox.com/settings/api_keys) page. ## Find your credentials **1. Open API Keys** Go to [Settings > API Keys](https://next.paubox.com/settings/api_keys). **2. Generate an API key** Click **Add API Key**. Under **Scope**, select **Paubox Email API**, then choose the verified sender **Domain** the key is for and enter a **Name**. Click **Add API Key** to create it. Copy the key immediately; it is displayed only once. **3. Note the base URL** All Email API requests go to the same base URL: ``` https://api.paubox.com/v1/email ``` ## Pass credentials in requests Include the `Authorization` header with every API call: ```bash theme={null} curl --request POST \ --url https://api.paubox.com/v1/email/messages \ --header 'Authorization: Bearer YOUR_API_KEY' \ --header 'Content-Type: application/json' ``` ### Bearer format (preferred) ``` Authorization: Bearer YOUR_API_KEY ``` ### Legacy Token format (also accepted) ``` Authorization: Token token=YOUR_API_KEY ``` Both formats are accepted. New integrations should use Bearer. ## Key rotation * Generate a new key before revoking an old one to avoid downtime. * Each domain can have multiple active keys, which is useful for rotating across services independently. * Revoke keys immediately if they are exposed or a team member with access leaves. > [!WARNING] > > Never commit API keys to source control. Use environment variables or a secrets manager to inject credentials at runtime. > > ```bash theme={null} > # Good > export PAUBOX_API_KEY=your_api_key > curl -H "Authorization: Bearer $PAUBOX_API_KEY" ... > > # Bad: do not do this > curl -H "Authorization: Bearer sk_live_abc123..." ... > ``` # Send bulk messages with the Email API Source: https://docs.paubox.com/email-api/bulk-messages openapi1 POST /bulk_messages Sends multiple messages in one request. Paubox recommends batches of 50 or fewer. Source tracking IDs are returned in the same order as the messages array. Each message is accepted for delivery as it is processed. If any message in the batch fails validation, the response contains only the errors, but messages that passed validation may already have been sent. Retrying the whole batch can send those messages again. # List dynamic templates with the Email API Source: https://docs.paubox.com/email-api/dynamic-templates openapi1 GET /dynamic_templates Retrieve dynamic templates for your organization. Without `page` or `items`, returns every template in a `templates` array. With `page` or `items`, returns a paginated `data` array with `page_info`. # Dynamic templates Source: https://docs.paubox.com/email-api/dynamic-templates-guide Create reusable Handlebars email templates and send personalized messages through the Paubox Email API. Dynamic templates let you store a Handlebars `.hbs` template on Paubox once and reference it by name when sending. Variable substitution, conditionals, and loops are resolved server-side before delivery, keeping your send requests small and consistent. ## Handlebars syntax Templates use [Handlebars](https://handlebarsjs.com) syntax. The most common constructs: | Syntax | Description | | :- | :- | | `{{variable}}` | Insert the value of a variable | | `{{#if condition}}...{{/if}}` | Conditional block (truthy check) | | `{{#each items}}...{{/each}}` | Loop over an array; use `{{this}}` for each item | ## Example template Save the following as `welcome.hbs`: ```handlebars theme={null} Hello {{name}}, Thank you for signing up{{#if plan}} for the {{plan}} plan{{/if}}. {{#if items}} Your selected items: {{#each items}}- {{this}} {{/each}} {{/if}} The Paubox Team ``` ## Workflow ### 1. Upload the template Upload your `.hbs` file via `POST /dynamic_templates`. The `data[name]` value becomes the identifier you use when sending. ```bash theme={null} curl -X POST https://api.paubox.com/v1/email/dynamic_templates \ -H "Authorization: Bearer YOUR_API_KEY" \ -F "data[name]=welcome" \ -F "data[body]=@welcome.hbs" ``` ### 2. Send a templated message Reference the template by name in `POST /templated_messages`. Pass variable values as a JSON string in `template_values`. ```bash theme={null} curl -X POST https://api.paubox.com/v1/email/templated_messages \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": { "template_name": "welcome", "template_values": "{\"name\":\"Jane\",\"plan\":\"Pro\",\"items\":[\"Email API\",\"HIPAA Compliance\"]}", "message": { "recipients": ["jane@example.com"], "headers": { "subject": "Welcome to Paubox", "from": "noreply@YOUR_DOMAIN.com" } } } }' ``` > [!NOTE] > > `template_values` must be a JSON-encoded **string**, not a JSON object. Stringify it before including it in the request body. ## Managing templates | Operation | API reference | | :- | :- | | List all templates | [List dynamic templates](/email-api/dynamic-templates) | | Create a template | [Create a dynamic template](/email-api/dynamic-templates/create) | | Get a template | [Get a dynamic template](/email-api/dynamic-templates/get) | | Update a template | [Update a dynamic template](/email-api/dynamic-templates/update) | | Delete a template | [Delete a dynamic template](/email-api/dynamic-templates/delete) | | Send using a template | [Send a templated message](/email-api/templated-messages) | # Create a dynamic template with the Email API Source: https://docs.paubox.com/email-api/dynamic-templates/create openapi1 POST /dynamic_templates Upload a new Handlebars template for dynamic content generation # Delete a dynamic template with the Email API Source: https://docs.paubox.com/email-api/dynamic-templates/delete openapi1 DELETE /dynamic_templates/{id} Delete a specific dynamic template by ID # Get a dynamic template with the Email API Source: https://docs.paubox.com/email-api/dynamic-templates/get openapi1 GET /dynamic_templates/{id} Retrieve a specific dynamic template by ID # Update a dynamic template with the Email API Source: https://docs.paubox.com/email-api/dynamic-templates/update openapi1 PATCH /dynamic_templates/{id} Update an existing Handlebars template # Errors Source: https://docs.paubox.com/email-api/errors HTTP error codes returned by the Paubox Email API, with common causes and fixes. The Paubox Email API uses standard HTTP status codes. Error responses include a JSON body describing the problem; see [Error response format](#error-response-format) below. ## Status codes | Code | Meaning | Common cause | | :- | :- | :- | | `200` | OK | Request succeeded | | `400` | Bad Request | Invalid request body: see checklist below | | `401` | Unauthorized | Missing or invalid API key | | `403` | Forbidden | API key valid but lacks permission for this action, or the account is in its first 24 hours after signup (see below) | | `404` | Not Found | Resource (e.g. tracking ID, or the `template_name` on a templated message) does not exist | | `422` | Unprocessable Entity | A dynamic template could not be rendered with the provided `template_values` | | `429` | Too Many Requests | Rate limit exceeded; see [Limits](/email-api/limits) | | `500` | Internal Server Error | Unexpected server-side error | | `502` | Bad Gateway | Upstream connectivity issue; retry with backoff | | `503` | Service Unavailable | Temporary outage; check [status.paubox.com](https://status.paubox.com) | | `504` | Gateway Timeout | Request timed out; retry with backoff | ## 400 Bad Request: debugging checklist A `400` usually means the request body is missing a required field or contains an invalid value. Work through this list: > [!WARNING] > > **The most common causes of 400 Bad Request:** > > * **`from` domain not verified**: the sender address must belong to a domain you have verified in [Settings > Domains](https://next.paubox.com/settings/domains). Sending from `@gmail.com` or any unverified domain always returns a 400. > * **Empty `recipients` array**: `data.message.recipients` must contain at least one valid email address. > * **Missing attachment field**: every attachment needs `fileName`, `contentType`, and `content`. Inline attachments also need `contentId` and an `image/*` `contentType`. > [!NOTE] > > Always include `data.message.content` with `text/plain`, `text/html`, or both. A send request with no `content` object is not rejected with a `400`; it returns a `500`. ## 401 Unauthorized The API key is missing or malformed. ```bash theme={null} # Check: is the Authorization header present and using a valid key? curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.paubox.com/v1/email/message_receipt?sourceTrackingId=YOUR_SOURCE_TRACKING_ID" ``` ## 403 Forbidden: new accounts New accounts are under review for 24 hours after signup. During that window, send requests (`/messages`, `/bulk_messages`, and `/templated_messages`) return `403` with the title `Account Under Review`. Wait until 24 hours after signup and try again, or contact [support@paubox.com](mailto:support@paubox.com). ## 429 Too Many Requests You have exceeded the rate limit for your plan. Back off and retry. See [Limits](/email-api/limits) for rate limit details. For high-volume sending, use the [bulk messages](/email-api/bulk-messages) endpoint (recommended max 50 per request) rather than looping over individual `/messages` calls. ## Error response format Most errors return an `errors` array. Each entry has a `code`, `title`, and `details`. ```json theme={null} { "errors": [ { "code": 400, "title": "Invalid from domain", "details": "From domain is not an approved sending domain for your account" } ] } ``` A request body that is missing a required field or uses the wrong type (for example, no `data.message.recipients`) is rejected before processing with a single error object instead of an array: ```json theme={null} { "code": 400, "title": "Invalid Request", "details": { "title": "Missing required params", "details": "Expected 'data.message.recipients' with Array type.", "code": 400 } } ``` # Limits and overage rates Source: https://docs.paubox.com/email-api/limits Sending limits, rate limits, and overage pricing for the Paubox Email API. ## Sending limits | Limit | Value | | :- | :- | | Max recipients per message | 100 | | Max request size (whole JSON body, including Base64-encoded attachments; for bulk, the whole request) | 50 MB | | Bulk messages (recommended max per request) | 50 | Base64 encoding adds about a third to file size, so a single message can carry roughly 37 MB of raw attachments. > [!NOTE] > > For high-volume sends, use the [bulk messages](/email-api/bulk-messages) endpoint rather than looping over individual `/messages` calls. Paubox recommends batches of 50 or fewer messages per request. If you receive a `429 Too Many Requests` response, back off and retry. See [Errors](/email-api/errors) for retry guidance. ## What to do if you've reached your limit You will be charged a small amount per-email for each email that you send beyond the limit of your current plan. Any overage charges will appear on an invoice of the month after any over-limit sending occurs. ## Paubox Email API overage costs If you go over your plan limits, here’s a breakdown of the overage costs you’ll incur: | **Plan Information** | **Monthly Plan Limits** | **Cost Per Extra Email** | | - | - | - | | Free | 300 | - | | Pro | 10,000 emails | \$0.0130 | | Pro | 30,000 emails | \$0.0130 | | Pro | 50,000 emails | \$0.0100 | | Pro | 100,000 emails | \$0.0098 | | Pro | Custom | - | # Get a message receipt with the Email API Source: https://docs.paubox.com/email-api/message-receipt openapi1 GET /message_receipt Retrieve delivery status, open tracking, and click tracking information for a sent message. Open, click, and unsubscribe data are included only when the corresponding tracking setting is enabled for your account. # Send a message with the Email API Source: https://docs.paubox.com/email-api/messages openapi1 POST /messages Send a single HIPAA compliant email with the Paubox Email API. Supports cc, bcc, custom headers, attachments, and open and link tracking overrides. # Migrate from Mailgun Source: https://docs.paubox.com/email-api/migrate-from-mailgun Switch from Mailgun to the Paubox Email API for HIPAA compliant transactional email. ## Why migrate HIPAA requires a signed Business Associate Agreement (BAA) with any vendor that handles Protected Health Information (PHI) in transit, including transactional email providers. While Mailgun will sign a Business Associate Agreements (BAAs), itʻs essentially a server-side BAA only. Email in transit over the internet is explicitly excluded from protection obligations, TLS is opportunistic (not enforced), and the customer is held responsible for encrypting PHI. This is the exact gap Paubox closes, email encryption with no fallback to plaintext, regardless of what the recipient's mail server supports. Paubox is purpose-built for HIPAA compliant email and signs a BAA with every customer. While Mailgun's API differs from Paubox's in a few key ways (notably request format and authentication), the concepts map cleanly and the migration is straightforward. ## What stays the same * REST API over HTTPS * Domain authentication: Paubox verifies your sending domain with an SPF record * SMTP as an alternative to the HTTP API * Webhook-based event notifications for delivery status * Per-domain sending configuration ## Key differences | Dimension | Mailgun | Paubox Email API | | :- | :- | :- | | Base URL | `https://api.mailgun.net/v3/YOUR_DOMAIN/messages` | `https://api.paubox.com/v1/email/messages` | | EU region URL | `https://api.eu.mailgun.net/v3/YOUR_DOMAIN/messages` | No region selection required | | Auth method | HTTP Basic Auth (username `api`, password = API key) | Bearer token: `Authorization: Bearer $PAUBOX_API_KEY` | | Request body format | `multipart/form-data` (`-F` flags in curl) | `application/json` (JSON body) | | Request body shape | Flat fields: `from`, `to`, `subject`, `html`, `text` | `data.message` object with `headers` and `content` keys | | SMTP host | `smtp.mailgun.org` | `smtp.paubox.com` | | SMTP username | Per-domain login (e.g. `postmaster@yourdomain.com`) | `apikey` (literal) | | SMTP password | Per-domain password from Mailgun Control Panel | Paubox API key | | SMTP port | 587 or 2525 | 587 (also supports 465, 25) | | Webhook events | accepted, delivered, opened, clicked, unsubscribed, permanent\_fail, temporary\_fail, complained | delivered, opened, temporary\_failure, permanent\_failure | | Batch send | Same endpoint with multiple `to` recipients or recipient variables | `/bulk_messages` endpoint, recommended max 50 per request | | TLS enforcement | Optional | On by default; opt out per message with `allowNonTLS` | ## Send a single email ```bash Mailgun (before) theme={null} curl -s --user 'api:$MAILGUN_API_KEY' \ https://api.mailgun.net/v3/YOUR_DOMAIN/messages \ -F from='provider@yourclinic.com' \ -F to='patient@example.com' \ -F subject='Your appointment summary' \ --form-string html='<p>See attached.</p>' ``` ```bash Paubox (after) theme={null} curl -X POST https://api.paubox.com/v1/email/messages \ -H "Authorization: Bearer $PAUBOX_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": { "message": { "recipients": ["patient@example.com"], "headers": { "subject": "Your appointment summary", "from": "provider@yourclinic.com" }, "content": { "text/html": "<p>See attached.</p>" } } } }' ``` > [!NOTE] > > **Note:** > > Mailgun uses `multipart/form-data` with HTTP Basic Auth. Paubox uses JSON with a Bearer token. Both the `Content-Type` header and the request body structure need to be updated. ## SMTP configuration ```js Mailgun (before) theme={null} const transporter = nodemailer.createTransport({ host: 'smtp.mailgun.org', port: 587, auth: { user: 'postmaster@yourdomain.com', // per-domain SMTP login from Mailgun Control Panel pass: process.env.MAILGUN_SMTP_PASSWORD, }, }); ``` ```js Paubox (after) theme={null} const transporter = nodemailer.createTransport({ host: 'smtp.paubox.com', port: 587, auth: { user: 'apikey', pass: process.env.PAUBOX_API_KEY, }, }); ``` > [!TIP] > > **Tip:** > > Mailgun SMTP credentials are per-domain and found under Sending → Domain Settings → SMTP credentials in the Mailgun Control Panel. Paubox uses the literal string `apikey` as username and your API key as password; no per-domain credential needed. ## Webhook event mapping | Mailgun event | Paubox event key | Notes | | :- | :- | :- | | `delivered` | `api_mail_log_delivered` | | | `opened` | `api_mail_log_opened` | | | `permanent_fail` | `api_mail_log_permanent_failure` | | | `temporary_fail` | `api_mail_log_temporary_failure` | | | `clicked` | No equivalent | Remove handler or no-op; poll click data via [Get message receipt](/email-api/message-receipt) | | `unsubscribed` | No equivalent | Turn on **Unsubscribe Tracking** in Settings > Email API; the [message receipt](/email-api/message-receipt) then includes `unsubscribed` | | `complained` | No equivalent | Remove handler | | `accepted` | No equivalent | Remove handler; `delivered` confirms acceptance | > [!NOTE] > > **Note:** > > Click counts are available by polling `GET /message_receipt?sourceTrackingId=...`; they are not delivered as a push webhook event. The receipt includes them only when **Click Tracking** is turned on in [Settings > Email API](https://next.paubox.com/settings/email_api). It is off by default. > [!NOTE] > > **Note:** > > Mailgun webhooks are configured per domain under Sending → Webhooks in the Control Panel, or via the Webhooks API. Paubox webhooks are configured in the Paubox dashboard under Settings → Webhooks. ## Migration checklist **1. Sign a BAA with Paubox** Required before go-live. Contact Paubox to initiate the Business Associate Agreement. **2. Create an account and verify your sending domain** Add your domain on the [Settings > Domains](https://next.paubox.com/settings/domains) page, add `include:_spf.paubox.com` to your domain's SPF record as shown on the domain's page, then click **Verify**. The record shown adds the Paubox include to your existing SPF entries rather than replacing them, so Mailgun keeps working while you migrate. See the [Quickstart guide](/email-api/quickstart) for step-by-step instructions. **3. Generate a Paubox API key** From the [Settings > API Keys](https://next.paubox.com/settings/api_keys) page, generate an API key with the **Paubox Email API** scope for your verified domain. All requests use the base URL `https://api.paubox.com/v1/email`. **4. Update base URL and authentication** Replace the Mailgun domain-namespaced URL and Basic Auth header with the Paubox endpoint and Bearer token. **5. Convert request body from form-data to JSON** Change `Content-Type` from `multipart/form-data` to `application/json` and restructure the body to use the `data.message` shape shown above. **6. Update SMTP credentials** If you use the SMTP path, update `host` to `smtp.paubox.com`, set `username` to the literal string `apikey`, and `password` to your Paubox API key. **7. Remap or remove webhook handlers** Update your webhook endpoint using the [event mapping table](#webhook-event-mapping) above. Remove handlers for `clicked`, `unsubscribed`, `complained`, and `accepted`. **8. Remove any EU region URL overrides** Paubox has a single global endpoint; `api.eu.mailgun.net` has no equivalent and should be removed. **9. Remove any code that disables TLS** Paubox sends every message over TLS by default and falls back to a Secure Portal message when the recipient server cannot accept TLS. Remove any `allowNonTLS: true` or equivalent settings unless you intend to allow non-TLS delivery, which is not HIPAA compliant for messages containing PHI. **10. Send a test message** Confirm delivery using the [Get message receipt](/email-api/message-receipt) endpoint with the `sourceTrackingId` returned from your test send. **11. Remove Mailgun DNS records** Once traffic has fully moved to Paubox, remove Mailgun's SPF entries and DKIM records from your DNS. Keep `include:_spf.paubox.com`. Paubox Email API domains need no DKIM record of their own. **12. Revoke Mailgun API keys** Once traffic has fully moved to Paubox, revoke your Mailgun API keys and SMTP credentials. ## Next steps > [card] [Quickstart guide](/email-api/quickstart) > > Full setup walkthrough from account creation to first send > [card] [Webhooks reference](/email-api/webhooks) > > Configure delivery event notifications > [card] [Batch send](/email-api/bulk-messages) > > Send multiple messages in one request (recommended max 50) > [card] [SMTP API](/email-api/smtp) > > Connect via SMTP instead of REST # Migrate from Postmark Source: https://docs.paubox.com/email-api/migrate-from-postmark Switch from Postmark to the Paubox Email API for HIPAA compliant transactional email. ## Why migrate Postmark does not sign Business Associate Agreements (BAAs). HIPAA requires a signed BAA with any vendor that handles Protected Health Information (PHI) in transit, including transactional email providers. Paubox is purpose-built for HIPAA compliant email and signs a BAA with every customer. The Postmark API uses familiar REST/JSON patterns, so the switch is straightforward for developers already comfortable with Postmark. ## What stays the same * REST API over HTTPS with JSON request bodies * API key authentication via a request header * Domain authentication: Paubox verifies your sending domain with an SPF record * SMTP as an alternative to the HTTP API * Webhook-based event notifications for delivery status ## Key differences | Dimension | Postmark | Paubox Email API | | :- | :- | :- | | Base URL | `https://api.postmarkapp.com/email` | `https://api.paubox.com/v1/email/messages` | | Auth header | `X-Postmark-Server-Token: $TOKEN` | `Authorization: Bearer $PAUBOX_API_KEY` | | Request body shape | `From`, `To`, `Subject`, `HtmlBody` flat keys | `data.message` object with `headers` and `content` keys | | SMTP host | `smtp.postmarkapp.com` | `smtp.paubox.com` | | SMTP username | Postmark server token (as username) | `apikey` (literal) | | SMTP password | Postmark server token (as password) | Paubox API key | | SMTP port | 587 or 2525 | 587 (also supports 465, 25) | | Webhook events | Delivery, Open, Click, Bounce, SpamComplaint, SubscriptionChange | delivered, opened, temporary\_failure, permanent\_failure | | Batch send | `/email/batch` endpoint, up to 500/request | `/bulk_messages` endpoint, recommended max 50 per request | | TLS enforcement | Optional | On by default; opt out per message with `allowNonTLS` | | Message streams | Transactional + Broadcast streams | Single unified API (no stream concept) | ## Send a single email ```bash Postmark (before) theme={null} curl -X POST https://api.postmarkapp.com/email \ -H "X-Postmark-Server-Token: $POSTMARK_SERVER_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "From": "provider@yourclinic.com", "To": "patient@example.com", "Subject": "Your appointment summary", "HtmlBody": "<p>See attached.</p>", "MessageStream": "outbound" }' ``` ```bash Paubox (after) theme={null} curl -X POST https://api.paubox.com/v1/email/messages \ -H "Authorization: Bearer $PAUBOX_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": { "message": { "recipients": ["patient@example.com"], "headers": { "subject": "Your appointment summary", "from": "provider@yourclinic.com" }, "content": { "text/html": "<p>See attached.</p>" } } } }' ``` ## SMTP configuration ```js Postmark (before) theme={null} const transporter = nodemailer.createTransport({ host: 'smtp.postmarkapp.com', port: 587, auth: { user: process.env.POSTMARK_SERVER_TOKEN, pass: process.env.POSTMARK_SERVER_TOKEN, }, }); ``` ```js Paubox (after) theme={null} const transporter = nodemailer.createTransport({ host: 'smtp.paubox.com', port: 587, auth: { user: 'apikey', pass: process.env.PAUBOX_API_KEY, }, }); ``` > [!TIP] > > **Tip:** > > Note the username change: Postmark uses the server token as both username and password. Paubox uses the literal string `apikey` as username and your API key as password. ## Webhook event mapping | Postmark event | Paubox event key | Notes | | :- | :- | :- | | `Delivery` | `api_mail_log_delivered` | | | `Open` | `api_mail_log_opened` | | | `Bounce` (hard) | `api_mail_log_permanent_failure` | | | `Bounce` (soft) | `api_mail_log_temporary_failure` | | | `Click` | No equivalent | Remove handler or no-op; poll click data via [Get message receipt](/email-api/message-receipt) | | `SpamComplaint` | No equivalent | Remove handler | | `SubscriptionChange` | No equivalent | Turn on **Unsubscribe Tracking** in Settings > Email API; the [message receipt](/email-api/message-receipt) then includes `unsubscribed` | > [!NOTE] > > **Note:** > > Click counts are available by polling `GET /message_receipt?sourceTrackingId=...`; they are not delivered as a push webhook event. The receipt includes them only when **Click Tracking** is turned on in [Settings > Email API](https://next.paubox.com/settings/email_api). It is off by default. ## Migration checklist **1. Sign a BAA with Paubox** Required before go-live. Contact Paubox to initiate the Business Associate Agreement. **2. Create an account and verify your sending domain** Add your domain on the [Settings > Domains](https://next.paubox.com/settings/domains) page, add `include:_spf.paubox.com` to your domain's SPF record as shown on the domain's page, then click **Verify**. The record shown adds the Paubox include to your existing SPF entries rather than replacing them, so Postmark keeps working while you migrate. See the [Quickstart guide](/email-api/quickstart) for step-by-step instructions. **3. Generate a Paubox API key** From the [Settings > API Keys](https://next.paubox.com/settings/api_keys) page, generate an API key with the **Paubox Email API** scope for your verified domain. All requests use the base URL `https://api.paubox.com/v1/email`. **4. Update base URL, auth header, and request body** Replace the Postmark endpoint and `X-Postmark-Server-Token` header with the Paubox endpoint and Bearer token. Restructure the request body to use the `data.message` shape shown above. **5. Remove MessageStream** Paubox has no stream concept. Remove the `"MessageStream"` field from all requests. **6. Update SMTP credentials** If you use the SMTP path, update `host` to `smtp.paubox.com`, set `username` to the literal string `apikey`, and `password` to your Paubox API key. **7. Remap or remove webhook handlers** Update your webhook endpoint using the [event mapping table](#webhook-event-mapping) above. Remove handlers for `Click`, `SpamComplaint`, and `SubscriptionChange`. **8. Remove any code that disables TLS** Paubox sends every message over TLS by default and falls back to a Secure Portal message when the recipient server cannot accept TLS. Remove any `allowNonTLS: true` or equivalent settings unless you intend to allow non-TLS delivery, which is not HIPAA compliant for messages containing PHI. **9. Send a test message** Confirm delivery using the [Get message receipt](/email-api/message-receipt) endpoint with the `sourceTrackingId` returned from your test send. **10. Remove Postmark DNS records** Once traffic has fully moved to Paubox, remove Postmark's SPF entries and DKIM records from your DNS. Keep `include:_spf.paubox.com`. Paubox Email API domains need no DKIM record of their own. **11. Revoke Postmark server tokens** Once traffic has fully moved to Paubox, revoke your Postmark server tokens. ## Next steps > [card] [Quickstart guide](/email-api/quickstart) > > Full setup walkthrough from account creation to first send > [card] [Webhooks reference](/email-api/webhooks) > > Configure delivery event notifications > [card] [Batch send](/email-api/bulk-messages) > > Send multiple messages in one request (recommended max 50) > [card] [SMTP API](/email-api/smtp) > > Connect via SMTP instead of REST # Migrate from Resend Source: https://docs.paubox.com/email-api/migrate-from-resend Switch from Resend to the Paubox Email API for HIPAA compliant transactional email. ## Why migrate Resend does not sign Business Associate Agreements (BAAs). HIPAA requires a signed BAA with any vendor that handles Protected Health Information (PHI) in transit, including transactional email providers. Paubox is purpose-built for HIPAA compliant email and signs a BAA with every customer, and TLS is on by default for every message. Resend's API uses familiar Bearer-auth and JSON patterns, so the switch is a small refactor for developers already comfortable with Resend. ## What stays the same * REST API over HTTPS with JSON request bodies * API key authentication via the `Authorization: Bearer` header * Domain authentication: Paubox verifies your sending domain with an SPF record * SMTP as an alternative to the HTTP API * Webhook-based event notifications for delivery status ## Key differences | Dimension | Resend | Paubox Email API | | :- | :- | :- | | Base URL | `https://api.resend.com/emails` | `https://api.paubox.com/v1/email/messages` | | Auth header | `Authorization: Bearer $RESEND_API_KEY` | `Authorization: Bearer $PAUBOX_API_KEY` | | Request body shape | `from`, `to`, `subject`, `html` flat keys | `data.message` object with `headers` and `content` keys | | Recipients field | `to` (array of strings) | `recipients` (array of strings, nested under `data.message`) | | SMTP host | `smtp.resend.com` | `smtp.paubox.com` | | SMTP username | `resend` (literal) | `apikey` (literal) | | SMTP port | 465 (recommended), 587, 25 | 587 (also supports 465, 25) | | Webhook events | email.sent, email.delivered, email.bounced, email.opened, email.clicked, email.complained, email.delivery\_delayed | delivered, opened, temporary\_failure, permanent\_failure | | Batch send | `/emails/batch` endpoint | `/bulk_messages` endpoint, recommended max 50 per request | | TLS enforcement | Optional | On by default; opt out per message with `allowNonTLS` | | BAA available | No | Yes (signed with every customer) | ## Send a single email ```bash Resend (before) theme={null} curl -X POST https://api.resend.com/emails \ -H "Authorization: Bearer $RESEND_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": "provider@yourclinic.com", "to": ["patient@example.com"], "subject": "Your appointment summary", "html": "<p>See attached.</p>" }' ``` ```bash Paubox (after) theme={null} curl -X POST https://api.paubox.com/v1/email/messages \ -H "Authorization: Bearer $PAUBOX_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": { "message": { "recipients": ["patient@example.com"], "headers": { "subject": "Your appointment summary", "from": "provider@yourclinic.com" }, "content": { "text/html": "<p>See attached.</p>" } } } }' ``` ## SMTP configuration ```js Resend (before) theme={null} const transporter = nodemailer.createTransport({ host: 'smtp.resend.com', port: 465, auth: { user: 'resend', pass: process.env.RESEND_API_KEY, }, }); ``` ```js Paubox (after) theme={null} const transporter = nodemailer.createTransport({ host: 'smtp.paubox.com', port: 587, auth: { user: 'apikey', pass: process.env.PAUBOX_API_KEY, }, }); ``` > [!TIP] > > **Tip:** > > Two changes are required: update `host` from `smtp.resend.com` to `smtp.paubox.com`, and change the literal username from `resend` to `apikey`. ## Webhook event mapping | Resend event | Paubox event key | Notes | | :- | :- | :- | | `email.delivered` | `api_mail_log_delivered` | | | `email.opened` | `api_mail_log_opened` | | | `email.bounced` | `api_mail_log_permanent_failure` | | | `email.delivery_delayed` | `api_mail_log_temporary_failure` | | | `email.clicked` | no equivalent | Remove handler or no-op; poll click data via [Get message receipt](/email-api/message-receipt) | | `email.complained` | no equivalent | Remove handler | | `email.sent` | no equivalent | Remove handler; `delivered` confirms acceptance | > [!NOTE] > > **Note:** > > Click counts are available by polling `GET /message_receipt?sourceTrackingId=...`; they are not delivered as a push webhook event. The receipt includes them only when **Click Tracking** is turned on in [Settings > Email API](https://next.paubox.com/settings/email_api). It is off by default. ## Migration checklist **1. Sign a BAA with Paubox** Required before go-live. Contact Paubox to initiate the Business Associate Agreement. **2. Create an account and verify your sending domain** Add your domain on the [Settings > Domains](https://next.paubox.com/settings/domains) page, add `include:_spf.paubox.com` to your domain's SPF record as shown on the domain's page, then click **Verify**. The record shown adds the Paubox include to your existing SPF entries rather than replacing them, so Resend keeps working while you migrate. See the [Quickstart guide](/email-api/quickstart) for step-by-step instructions. **3. Generate a Paubox API key** From the [Settings > API Keys](https://next.paubox.com/settings/api_keys) page, generate an API key with the **Paubox Email API** scope for your verified domain. All requests use the base URL `https://api.paubox.com/v1/email`. **4. Update base URL, auth header, and request body** Apply the changes shown in the [Key differences](#key-differences) table and [Send a single email](#send-a-single-email) section above. Note that recipients move from a top-level `to` array into `data.message.recipients`. **5. Update SMTP credentials** If you use the SMTP path, update `host` to `smtp.paubox.com` and change the literal username from `resend` to `apikey`. See [SMTP configuration](#smtp-configuration) above. **6. Remap or remove webhook handlers** Update your webhook endpoint using the [event mapping table](#webhook-event-mapping) above. Remove handlers for `email.clicked`, `email.complained`, and `email.sent`. **7. Remove any code that disables TLS** Paubox sends every message over TLS by default and falls back to a Secure Portal message when the recipient server cannot accept TLS. Remove any `allowNonTLS: true` or equivalent settings unless you intend to allow non-TLS delivery, which is not HIPAA compliant for messages containing PHI. **8. Send a test message** Confirm delivery using the [Get message receipt](/email-api/message-receipt) endpoint with the `sourceTrackingId` returned from your test send. **9. Remove Resend DNS records** Once traffic has fully moved to Paubox, remove Resend's SPF entries and DKIM records from your DNS. Keep `include:_spf.paubox.com`. Paubox Email API domains need no DKIM record of their own. **10. Revoke Resend API keys** Once traffic has fully moved to Paubox, revoke your Resend API keys. ## Next steps > [card] [Quickstart guide](/email-api/quickstart) > > Full setup walkthrough from account creation to first send > [card] [Webhooks reference](/email-api/webhooks) > > Configure delivery event notifications > [card] [Batch send](/email-api/bulk-messages) > > Send multiple messages in one request (recommended max 50) > [card] [SMTP API](/email-api/smtp) > > Connect via SMTP instead of REST # Migrate from SendGrid Source: https://docs.paubox.com/email-api/migrate-from-sendgrid Switch from SendGrid v3 to the Paubox Email API for HIPAA compliant transactional email. ## Why migrate SendGrid does not sign Business Associate Agreements (BAAs) for standard transactional email accounts. HIPAA requires a signed BAA with any vendor that handles Protected Health Information (PHI) in transit, including email providers. Paubox is purpose-built for HIPAA compliant email and signs a BAA with every customer. The API is REST-based and follows patterns SendGrid developers will recognize, so the switch is straightforward. ## What stays the same * REST API over HTTPS with JSON request bodies * Domain authentication: Paubox verifies your sending domain with an SPF record * API key authentication via the `Authorization` header * SMTP as an alternative to the HTTP API (same `apikey` / API-key-as-password pattern) * Webhook-based event notifications for delivery status ## Key differences | Dimension | SendGrid v3 | Paubox Email API | | :- | :- | :- | | Base URL | `https://api.sendgrid.com/v3/mail/send` | `https://api.paubox.com/v1/email` | | Auth header | `Authorization: Bearer $SENDGRID_API_KEY` | `Authorization: Bearer $PAUBOX_API_KEY` | | Request body shape | `personalizations` array with nested `to`/`subject` | `data.message` object with `headers` and `content` keys | | SMTP host | `smtp.sendgrid.net` | `smtp.paubox.com` | | SMTP username | `apikey` (literal) | `apikey` (literal, same pattern) | | SMTP port | 587 | 587 (also supports 465, 25) | | Webhook events | processed, delivered, open, click, bounce, spam\_report, unsubscribe | delivered, opened, temporary\_failure, permanent\_failure | | Batch send | up to 1,000 personalizations per request | `/bulk_messages` endpoint, recommended max 50 per request | | TLS enforcement | optional (can be disabled) | on by default; opt out per message with `allowNonTLS` | ## Send a single email ```bash SendGrid (before) theme={null} curl -X POST https://api.sendgrid.com/v3/mail/send \ -H "Authorization: Bearer $SENDGRID_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "personalizations": [{"to": [{"email": "patient@example.com"}]}], "from": {"email": "provider@yourclinic.com"}, "subject": "Your appointment summary", "content": [{"type": "text/html", "value": "<p>See attached.</p>"}] }' ``` ```bash Paubox (after) theme={null} curl -X POST https://api.paubox.com/v1/email/messages \ -H "Authorization: Bearer $PAUBOX_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": { "message": { "recipients": ["patient@example.com"], "headers": { "subject": "Your appointment summary", "from": "provider@yourclinic.com" }, "content": { "text/html": "<p>See attached.</p>" } } } }' ``` ## SMTP configuration The only required change is `host`. The username/password pattern is identical. ```js SendGrid (before) theme={null} const transporter = nodemailer.createTransport({ host: 'smtp.sendgrid.net', port: 587, auth: { user: 'apikey', pass: process.env.SENDGRID_API_KEY, }, }); ``` ```js Paubox (after) theme={null} const transporter = nodemailer.createTransport({ host: 'smtp.paubox.com', port: 587, auth: { user: 'apikey', pass: process.env.PAUBOX_API_KEY, }, }); ``` > [!TIP] > > **Tip:** > > `port`, `user`, and the auth pattern are unchanged. Only `host` needs to be updated. ## Webhook event mapping | SendGrid event | Paubox event key | Notes | | :- | :- | :- | | `delivered` | `api_mail_log_delivered` | | | `open` | `api_mail_log_opened` | | | `bounce` (hard) | `api_mail_log_permanent_failure` | | | `bounce` (soft) / `deferred` | `api_mail_log_temporary_failure` | | | `click` | No equivalent | Remove handler or no-op; poll click data via [Get message receipt](/email-api/message-receipt) | | `spam_report` | No equivalent | Remove handler | | `processed` | No equivalent | Remove handler; `delivered` confirms acceptance | | `unsubscribe` | No equivalent | Turn on **Unsubscribe Tracking** in Settings > Email API; the [message receipt](/email-api/message-receipt) then includes `unsubscribed` | > [!NOTE] > > **Note:** > > Click counts are available by polling `GET /message_receipt?sourceTrackingId=...`; they are not delivered as a push webhook event. The receipt includes them only when **Click Tracking** is turned on in [Settings > Email API](https://next.paubox.com/settings/email_api). It is off by default. ## Migration checklist **1. Sign a BAA with Paubox** Required before go-live. Contact Paubox to initiate the Business Associate Agreement. **2. Create an account and verify your sending domain** Add your domain on the [Settings > Domains](https://next.paubox.com/settings/domains) page, add `include:_spf.paubox.com` to your domain's SPF record as shown on the domain's page, then click **Verify**. The record shown adds the Paubox include to your existing SPF entries rather than replacing them, so SendGrid keeps working while you migrate. See the [Quickstart guide](/email-api/quickstart) for step-by-step instructions. **3. Generate a Paubox API key** From the [Settings > API Keys](https://next.paubox.com/settings/api_keys) page, generate an API key with the **Paubox Email API** scope for your verified domain. All requests use the base URL `https://api.paubox.com/v1/email`. **4. Update base URL, auth header, and request body** Apply the changes shown in the [Key differences](#key-differences) table and [Send a single email](#send-a-single-email) section above. **5. Update SMTP credentials** If you use the SMTP path, update `host` to `smtp.paubox.com`. See [SMTP configuration](#smtp-configuration) above. **6. Remap or remove webhook handlers** Update your webhook endpoint using the [event mapping table](#webhook-event-mapping) above. Remove handlers for `click`, `spam_report`, `processed`, and `unsubscribe`. **7. Remove any code that disables TLS** Paubox sends every message over TLS by default and falls back to a Secure Portal message when the recipient server cannot accept TLS. Remove any `allowNonTLS: true` or equivalent settings unless you intend to allow non-TLS delivery, which is not HIPAA compliant for messages containing PHI. **8. Send a test message** Confirm delivery using the [Get message receipt](/email-api/message-receipt) endpoint with the `sourceTrackingId` returned from your test send. **9. Remove SendGrid DNS records** Once traffic has fully moved to Paubox, remove SendGrid's SPF entries and DKIM records from your DNS. Keep `include:_spf.paubox.com`. Paubox Email API domains need no DKIM record of their own. **10. Revoke SendGrid API keys** Once traffic has fully moved to Paubox, revoke your SendGrid API keys. ## Next steps > [card] [Quickstart guide](/email-api/quickstart) > > Full setup walkthrough from account creation to first send > [card] [Webhooks reference](/email-api/webhooks) > > Configure delivery event notifications > [card] [Batch send](/email-api/bulk-messages) > > Send multiple messages in one request (recommended max 50) > [card] [SMTP API](/email-api/smtp) > > Connect via SMTP instead of REST # Migrate from Amazon SES Source: https://docs.paubox.com/email-api/migrate-from-ses Switch from Amazon SES to the Paubox Email API for HIPAA compliant transactional email. ## Why migrate AWS will sign a Business Associate Agreement (BAA) that covers SES as a service, but the BAA does not protect Protected Health Information (PHI) in the body of the mail once it leaves AWS. SES TLS enforcement defaults to opportunistic (`TlsPolicy: OPTIONAL`), so messages silently fall back to plaintext when the recipient server doesn't advertise STARTTLS; the customer carries the encryption-in-transit obligation. Paubox closes that gap with TLS on by default, an automatic Secure Portal fallback when the recipient cannot accept encrypted mail, and a BAA signed with every customer. The send-side API is REST/JSON and the migration is straightforward as most patterns map one-to-one. ## What stays the same * REST API over HTTPS with JSON request bodies (when using SESv2; SES v1 form-encoded callers will move to JSON) * Domain authentication: Paubox verifies your sending domain with an SPF record * SMTP as an alternative to the HTTP API * Webhook-based event notifications for delivery status * Per-domain sending configuration ## Key differences | Dimension | Amazon SES (SESv2) | Paubox Email API | | :- | :- | :- | | Base URL | `https://email.{region}.amazonaws.com/v2/email/outbound-emails` | `https://api.paubox.com/v1/email/messages` | | Region selection | Required (`us-east-1`, `eu-west-1`, …) | Single global endpoint, no region | | Auth method | AWS SigV4 (access key + secret + region, or IAM role) | Bearer token: `Authorization: Bearer $PAUBOX_API_KEY` | | SDK | `@aws-sdk/client-sesv2`, `boto3` `sesv2`, `Aws::SESV2`, etc. | `paubox-node`, `paubox-python3`, `paubox-ruby`, `paubox-php`, `paubox-java`, `paubox-csharp`, or plain `fetch` / `requests` | | Request body shape | `Content.Simple.Subject.Data` / `Body.Html.Data` / `Destination.ToAddresses[]` | `data.message.headers.subject` / `content["text/html"]` / `recipients[]` | | Attachments | Raw MIME via `SendRawEmail` only | First-class `data.message.attachments[]` with base64 `content` | | Bulk send | `SendBulkEmail` (templated only, up to 50 destinations) | `/bulk_messages` endpoint, recommended max 50 per request | | Templates | SES templates (`CreateTemplate` API, Handlebars-style syntax) | Paubox Dynamic Templates (`/dynamic_templates` CRUD, Handlebars) | | SMTP host | `email-smtp.{region}.amazonaws.com` | `smtp.paubox.com` | | SMTP credentials | IAM-user-derived SMTP username + password (separate from the AWS API key) | Literal string `apikey` as username, Paubox API key as password | | SMTP port | 25, 465, 587, or 2587 | 587 (also supports 465, 25) | | TLS enforcement | `TlsPolicy: OPTIONAL \| REQUIRE` (per configuration set) | On by default; opt out per message with `allowNonTLS` | | Delivery feedback | SNS topic subscription → HTTPS endpoint | Paubox webhooks (HTTPS POST directly to your endpoint) | | Message ID returned | `MessageId` | `sourceTrackingId` | ## Send a single email ```js Amazon SES (before) theme={null} import { SESv2Client, SendEmailCommand } from "@aws-sdk/client-sesv2"; const ses = new SESv2Client({ region: process.env.AWS_REGION }); await ses.send( new SendEmailCommand({ FromEmailAddress: "provider@yourclinic.com", Destination: { ToAddresses: ["patient@example.com"] }, Content: { Simple: { Subject: { Data: "Your appointment summary" }, Body: { Html: { Data: "<p>See attached.</p>" } }, }, }, }), ); ``` ```bash Paubox (after) theme={null} curl -X POST https://api.paubox.com/v1/email/messages \ -H "Authorization: Bearer $PAUBOX_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "data": { "message": { "recipients": ["patient@example.com"], "headers": { "subject": "Your appointment summary", "from": "provider@yourclinic.com" }, "content": { "text/html": "<p>See attached.</p>" } } } }' ``` > [!NOTE] > > **Note:** > > SES uses AWS SigV4 over the AWS credential chain (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`, or an IAM role). Paubox uses a single Bearer token. After cutover, remove the AWS SDK dependency and any AWS credentials scoped to `ses:SendEmail` from your runtime environment. ## SMTP configuration ```js Amazon SES (before) theme={null} const transporter = nodemailer.createTransport({ host: "email-smtp.us-east-1.amazonaws.com", port: 587, auth: { user: process.env.SES_SMTP_USERNAME, // IAM-derived SMTP username pass: process.env.SES_SMTP_PASSWORD, // IAM-derived SMTP password }, }); ``` ```js Paubox (after) theme={null} const transporter = nodemailer.createTransport({ host: "smtp.paubox.com", port: 587, auth: { user: "apikey", pass: process.env.PAUBOX_API_KEY, }, }); ``` > [!TIP] > > **Tip:** > > SES SMTP credentials are not the same as your AWS API key; they are derived from a dedicated IAM user via the SES console. After traffic has moved to Paubox, delete that IAM user so the SMTP credential is fully revoked. ## Webhook event mapping SES does not push HTTP webhooks directly; bounces, complaints, and deliveries are published to an SNS topic that fans out to an HTTPS subscription. Paubox replaces both layers with a direct HTTPS POST to your endpoint. | SES SNS event | Paubox event key | Notes | | :- | :- | :- | | `Delivery` | `api_mail_log_delivered` | | | `Open` | `api_mail_log_opened` | | | `Bounce` (`bounceType: Permanent`) | `api_mail_log_permanent_failure` | | | `Bounce` (`bounceType: Transient`) | `api_mail_log_temporary_failure` | | | `Click` | no equivalent | Poll click data via [Get message receipt](/email-api/message-receipt) | | `Complaint` | no equivalent | Remove handler | | `Reject` | no equivalent | Paubox returns rejections synchronously in the POST response, not as a webhook | | `Send` | no equivalent | `delivered` confirms acceptance; remove handler | > [!NOTE] > > **Note:** > > Click counts are available by polling `GET /message_receipt?sourceTrackingId=...`; they are not delivered as a push webhook event. The receipt includes them only when **Click Tracking** is turned on in [Settings > Email API](https://next.paubox.com/settings/email_api). It is off by default. > [!NOTE] > > **Note:** > > Paubox webhooks POST directly to your HTTPS endpoint. There is no intermediary SNS topic, so the JSON envelope is flatter than the SES → SNS → subscription payload. Configure endpoints in the Paubox dashboard under Settings → Webhooks. See the [Webhooks reference](/email-api/webhooks) for the payload shape. ## Template migration If you use SES templates (`CreateTemplate` / `SendTemplatedEmail` / `SendBulkTemplatedEmail`), recreate each one as a Paubox Dynamic Template. Both systems use Handlebars-style `{{variable}}` syntax, so most template bodies port verbatim. **1. Export each SES template** Run `aws ses get-template --template-name <name>` (or `aws sesv2 get-email-template`) and capture the `HtmlPart` field. A Paubox dynamic template holds only a `name` and an HTML `body`. Paubox generates the plain-text part from the HTML when it sends, so `TextPart` isn't needed. Move the `Subject` into each send's `headers.subject`; template variables are not rendered in the subject. **2. Create the Paubox Dynamic Template** POST each template to `/dynamic_templates` with its name as `data[name]` and the `HtmlPart` as `data[body]`. See the [Dynamic templates reference](/email-api/dynamic-templates) for the request format. **3. Switch from `SendTemplatedEmail` to templated messages** Replace `SendTemplatedEmail` / `SendBulkTemplatedEmail` calls with `POST /templated_messages`, passing the template name in `data.template_name` and the variable values as a JSON-encoded string in `data.template_values`. `/bulk_messages` does not accept templates, so send one templated request per message. See the [Dynamic templates guide](/email-api/dynamic-templates-guide) for an example. ## Migration checklist **1. Sign a BAA with Paubox** Required before go-live. Contact Paubox to initiate the Business Associate Agreement. **2. Create an account and verify your sending domain** Add your domain on the [Settings > Domains](https://next.paubox.com/settings/domains) page, add `include:_spf.paubox.com` to your domain's SPF record as shown on the domain's page, then click **Verify**. The record shown adds the Paubox include to your existing SPF entries rather than replacing them, so SES keeps working while you migrate. See the [Quickstart guide](/email-api/quickstart) for step-by-step instructions. **3. Generate a Paubox API key** From the [Settings > API Keys](https://next.paubox.com/settings/api_keys) page, generate an API key with the **Paubox Email API** scope for your verified domain. All requests use the base URL `https://api.paubox.com/v1/email`. **4. Replace the AWS SDK call with a Paubox request** Remove `@aws-sdk/client-ses` / `@aws-sdk/client-sesv2` (or the `boto3` / `Aws::SESV2` equivalent) and call Paubox via `fetch` / one of the Paubox SDKs. Restructure the request body to use the `data.message` shape shown above. **5. Remove AWS credentials from runtime config** Drop `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`, and any IAM role permissions scoped to `ses:SendEmail` / `ses:SendRawEmail` / `ses:SendBulkEmail`. **6. Update SMTP credentials** If you use the SMTP path, update `host` to `smtp.paubox.com`, set `username` to the literal string `apikey`, and `password` to your Paubox API key. Delete the IAM user that was created for SES SMTP credentials. **7. Recreate SES templates as Paubox Dynamic Templates** See [Template migration](#template-migration) above. **8. Tear down the SNS topic and HTTPS subscription** Remap your bounce / complaint / delivery handler to the Paubox webhook payload using the [event mapping table](#webhook-event-mapping) above, then delete the SNS topic and configuration-set event destination used for SES feedback. **9. Remove any TLS policy overrides** Paubox applies TLS by default; remove `TlsPolicy: OPTIONAL` or `TlsPolicy: REQUIRE` from any SES configuration set you were referencing. **10. Send a test message** Confirm delivery using the [Get message receipt](/email-api/message-receipt) endpoint with the `sourceTrackingId` returned from your test send. **11. Remove SES DNS records** Once traffic has fully moved to Paubox, remove SES's SPF entries and DKIM records from your DNS. Keep `include:_spf.paubox.com`. Paubox Email API domains need no DKIM record of their own. **12. Revoke AWS credentials** Once traffic has fully moved to Paubox, delete the IAM user and access keys used by the SES integration. ## Next steps > [card] [Quickstart guide](/email-api/quickstart) > > Full setup walkthrough from account creation to first send > [card] [Webhooks reference](/email-api/webhooks) > > Configure delivery event notifications > [card] [Batch send](/email-api/bulk-messages) > > Send multiple messages in one request (recommended max 50) > [card] [SMTP API](/email-api/smtp) > > Connect via SMTP instead of REST # Quickstart guide Source: https://docs.paubox.com/email-api/quickstart In this Quickstart, send your first HIPAA compliant email via Paubox Email API in under 5 minutes. **1. Sign up and create a Paubox account** It's free to [sign up](https://next.paubox.com/signup?order_name=paubox_email_api_order\&plan_name=standard\&unit_count=300\&plan_type=annual) and to send up to 300 emails per month, with a BAA included. > [!NOTE] > > **Note:** > > If you send more than 300 emails in one month, you will be automatically moved to the appropriate [pricing tier](https://www.paubox.com/pricing/paubox-email-api) and billed the annual cost. **2. Add and verify your domain** Once you have a Paubox account, go to the [Settings > Domains](https://next.paubox.com/settings/domains) page and add the domain you'll be sending from. Paubox verifies domain ownership via your domain's **SPF record**. Paubox will display the SPF value to add at your DNS provider (e.g., Route 53, Cloudflare, GoDaddy). Add or update the SPF record in your domain's DNS, then return to the Settings > Domains page and click **Verify**. > [!TIP] > > **Tip:** > > Most DNS providers propagate DNS changes within a few minutes, but allow up to 48 hours. If verification fails immediately, wait a few minutes and try again. **3. Generate an API key** From the [Settings > API Keys](https://next.paubox.com/settings/api_keys) page, click **Add API Key**. Select the **Paubox Email API** scope, choose the domain you verified in the previous step, give the key a name, and click **Add API Key**. Copy the key now: it is shown only once. If you lose it, you will have to generate a new one. All Email API requests use the same base URL: ``` https://api.paubox.com/v1/email ``` You will use this base URL in every API request. **4. Send your first email** Use the following curl command to send a test email. Replace `YOUR_API_KEY` and the `from` address with your actual values. The `from` address must match your verified domain. > [!NOTE] > > New accounts are under review for 24 hours after signup. Send requests made during that window return `403 Account Under Review`; try again once 24 hours have passed. ```bash theme={null} curl --request POST \ --url https://api.paubox.com/v1/email/messages \ --header 'Authorization: Bearer YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "data": { "message": { "recipients": ["recipient@example.com"], "headers": { "subject": "Hello from Paubox", "from": "sender@yourdomain.com" }, "content": { "text/plain": "Hello world", "text/html": "<html><body><h1>Hello world</h1></body></html>" } } } }' ``` > [!NOTE] > > **What success looks like:** > > A `200 OK` response confirms your message was accepted for delivery: > > ```json theme={null} > { > "sourceTrackingId": "3d38ab13-0af8-4028-bd45-52e882e0d584", > "customHeaders": {}, > "data": "Service OK" > } > ``` > > Save the `sourceTrackingId`; you can use it to check delivery status later. **5. Integrate via SDK** Official SDKs handle authentication and request formatting for you. Choose your language: * [C#](/csharp-sdk/quickstart) * [Go](/go-sdk/quickstart) * [Java](/java-sdk/quickstart) * [Node.js](/node-sdk/quickstart) * [Perl](/perl-sdk/quickstart) * [PHP](/php-sdk/quickstart) * [Python](/python-sdk/quickstart) * [Rails](/rails-sdk/quickstart) * [Ruby](/ruby-sdk/quickstart) * [Rust](/rust-sdk/quickstart) > [!TIP] > > Prefer the terminal? See the [CLI quickstart](/cli/quickstart) to send email without writing code. ## Next steps > [card] [Track message status](/email-api/message-receipt) > > Check delivery status using a sourceTrackingId > [card] [Send attachments](/email-api/attachments) > > Add files to your messages via the REST API > [card] [MCP server](/mcp-server/quickstart) > > Use Paubox from AI agents and editors via MCP # Receiving email Source: https://docs.paubox.com/email-api/receiving Receive inbound email through the Paubox Email API: provision domains and retrieve messages programmatically. Paubox Receiving lets you accept inbound email via the Email API. Provision a domain, and pull messages and attachments via REST, with no mail server to run. ## How it works 1. **Enable inbound email.** A receiving domain is automatically provisioned as a subdomain of `inbound.paubox.email` (e.g. `gentle-dolphin.inbound.paubox.email`). A catch-all inbox handles mail to any address on the domain. 2. **Receive email.** Anyone can send to any address on your domain. Messages are stored and available via the API within seconds. 3. **Retrieve messages.** List, read, and download attachments through the API. Cursor-based pagination keeps large inboxes fast. 4. **Get notified.** Subscribe to the `email.inbound.received` webhook event in the Paubox Dashboard to receive a POST to your endpoint each time an email arrives. The Webhook Endpoints API doesn't accept this event, and it isn't yet available on every account; see [Webhooks](/email-api/webhooks#managing-webhook-endpoints-via-the-api). ## Resources | Resource | Description | | :- | :- | | [Domains](/email-api/receiving/list-domains) | Provision and manage `*.inbound.paubox.email` subdomains | | [Emails](/email-api/receiving/list-emails) | List received messages, read content, and download attachments | | [Webhooks](/email-api/webhooks) | Subscribe to `email.inbound.received` for real-time delivery notifications | ## Limits * Domains per account: contact support for limits above the default. * Email retrieval: paginated, up to 100 per request. * Attachment download: returns raw bytes; size limited by the original message. # Create a receiving domain with the Email API Source: https://docs.paubox.com/email-api/receiving/create-domain openapi1 POST /receiving/domains Provisions a new receiving domain under `inbound.paubox.email`. DNS records are configured automatically. # Create a mailbox with the Email API Source: https://docs.paubox.com/email-api/receiving/create-mailbox openapi1 POST /receiving/domains/{domain_id}/mailboxes Creates a new mailbox on a receiving domain. # Delete a receiving domain with the Email API Source: https://docs.paubox.com/email-api/receiving/delete-domain openapi1 DELETE /receiving/domains/{id} Delete a receiving domain by ID. Look up domain IDs with the List receiving domains endpoint. # Delete a mailbox with the Email API Source: https://docs.paubox.com/email-api/receiving/delete-mailbox openapi1 DELETE /receiving/domains/{domain_id}/mailboxes/{id} Delete a mailbox from a receiving domain. Requires both the receiving domain ID and the mailbox ID. # Download an attachment with the Email API Source: https://docs.paubox.com/email-api/receiving/download-attachment openapi1 GET /receiving/{email_id}/attachments/{attachment_id} Downloads a received email attachment as raw bytes. # Get a receiving domain with the Email API Source: https://docs.paubox.com/email-api/receiving/get-domain openapi1 GET /receiving/domains/{id} Retrieve a receiving domain by ID, including its state and DNS zone file. # Get a received email with the Email API Source: https://docs.paubox.com/email-api/receiving/get-email openapi1 GET /receiving/{email_id} Returns the full content of a single received email, including headers, body, and attachment metadata. # Get a mailbox with the Email API Source: https://docs.paubox.com/email-api/receiving/get-mailbox openapi1 GET /receiving/domains/{domain_id}/mailboxes/{id} Retrieve a mailbox on a receiving domain by ID, including its email address, storage quota, and creation time. # List email attachments with the Email API Source: https://docs.paubox.com/email-api/receiving/list-attachments openapi1 GET /receiving/{email_id}/attachments Returns attachment metadata for a received email. # List receiving domains with the Email API Source: https://docs.paubox.com/email-api/receiving/list-domains openapi1 GET /receiving/domains Returns all receiving domains for the authenticated account. # List received emails with the Email API Source: https://docs.paubox.com/email-api/receiving/list-emails openapi1 GET /receiving Returns received emails across all active receiving domains, sorted by most recent. To fetch the next page, pass the `email_id` of the last email on the current page as `after`. `has_more` is true while more emails remain. # List mailboxes with the Email API Source: https://docs.paubox.com/email-api/receiving/list-mailboxes openapi1 GET /receiving/domains/{domain_id}/mailboxes Returns all mailboxes for a receiving domain. # Cancel a scheduled message with the Email API Source: https://docs.paubox.com/email-api/scheduled-send/cancel openapi1 POST /schedule/{sourceTrackingId}/cancel Cancel a scheduled message before it is sent. Only messages still in the pending state can be cancelled. # Get scheduled message status with the Email API Source: https://docs.paubox.com/email-api/scheduled-send/get openapi1 GET /schedule/{sourceTrackingId} Check a scheduled message's state (pending, processing, sent, cancelled, or failed) along with its scheduled, sent, and cancelled times. # Reschedule a message with the Email API Source: https://docs.paubox.com/email-api/scheduled-send/reschedule openapi1 PATCH /schedule/{sourceTrackingId} Move a pending scheduled message to a new send time. The new time must be in the future and within 30 days; only pending messages can be rescheduled. # Schedule a message with the Email API Source: https://docs.paubox.com/email-api/scheduled-send/schedule openapi1 POST /schedule Schedule an email for delivery at a future UTC time, up to 30 days ahead. Returns a sourceTrackingId you can use to check, reschedule, or cancel the send. # SMTP API Source: https://docs.paubox.com/email-api/smtp Send email through the Paubox Email API over SMTP: connect to smtp.paubox.com on port 587, 465, or 25, with TLS options and rate limits. ## Connect to Paubox Email API via SMTP To send email through Paubox SMTP API, follow these steps: **Step 1** **Generate a Paubox Email API key from the** [**Settings > API Keys**](https://next.paubox.com/settings/api_keys) **page.** **Step 2** **Configure the SMTP server host** to `smtp.paubox.com`.\ This is often labeled as the **SMTP relay** or **outgoing mail server** in most email clients. **Step 3** **Set your username** to the literal string `apikey`. > [!NOTE] > > **Note:** > > this should be the exact word `"apikey"`, **not** the API key you generated. **Step 4** **Use your API key** as the SMTP password. **Step 5** **Choose the appropriate port**, typically `587`, unless your network requires another. > [!TIP] > > **Tip:** > > If you're pasting a base64-encoded API key, double-check for any extra spaces or line breaks.\ > These can inadvertently appear when copying from certain terminals or editors, and they will prevent authentication.\ > Since SMTP is a line-based protocol, even a stray newline can result in failure. ## Available SMTP Ports Choose the correct port based on your desired level of security: * For **TLS** connections, use:\ `25` or `587` * For **SSL/TLS** connections, use:\ `465` > [!TIP] > > **Tip:** > > If you're not sure which one to use, **587 with STARTTLS** is the most widely supported and recommended option. ## Sending Mail via SMTP Once your SMTP connection is set up, you’re ready to construct and send email messages using your preferred client, service, or library. * The `MAIL FROM` address must be on the domain your API key belongs to. Any other domain is rejected with `550 5.1.7 Unauthorized sender domain`. * To send a message as a Paubox Secure Message (the recipient gets a pickup notification with a link), add an `X-Force-Secure-Msg` header to the message. The header name is case-sensitive. ## Rate Limits To avoid delivery interruptions, be aware of Paubox SMTP usage thresholds: * By default, a single IP address may open up to **500 SMTP connections per minute**. Connections beyond that are refused with `421 4.7.0 Too many connections or commands. Try again later.`; wait and retry. ## Avoid Direct IP Usage Always reference the host as `smtp.paubox.com`; do **not** use direct IP addresses.\ Paubox’s infrastructure may change without warning, and relying on hardcoded IPs could cause unexpected delivery issues in the future. # Send a templated message with the Email API Source: https://docs.paubox.com/email-api/templated-messages openapi1 POST /templated_messages Send an email using a dynamic template with variable substitution # Webhooks Source: https://docs.paubox.com/email-api/webhooks Receive real-time Paubox Email API events for delivery, opens, failures, and inbound mail, with payloads, retry behavior, and signature verification. Paubox webhooks push event notifications to an HTTPS URL you own. Configure them in the [Paubox Dashboard](https://next.paubox.com/emailapi/webhooks) or programmatically via the [Webhook Endpoints API](/email-api/webhooks/list). > [!WARNING] > > **Organization-wide scope:** Webhooks are triggered at the organization level. Events from **all domains** in your organization will be sent to the configured webhook URL; there is no per-domain filtering. Design your handler to inspect the `from` field in the payload (or `payload.data.domain` for inbound mail) if you need to route events by domain. ## Webhook endpoint fields * **URL**: An HTTPS URL you own, to which webhook payloads are delivered. * **Events**: One or more event types to subscribe to. * **Signing secret**: Endpoints subscribed to inbound mail get a generated signing secret (`whsec_...`), shown once when you create the endpoint. See [Verifying webhook signatures](#verifying-webhook-signatures). * **Active**: Whether the endpoint receives deliveries. Defaults to `true`. ## Available events | **Event Name** | **Event Key** | **Trigger** | | :- | :- | :- | | Delivered | api\_mail\_log\_delivered | When an outbound message is delivered | | Temporary Failure | api\_mail\_log\_temporary\_failure | On soft bounce of an outbound message | | Permanent Failure | api\_mail\_log\_permanent\_failure | On hard bounce of an outbound message | | Opened | api\_mail\_log\_opened | On opening of an outbound message | | Inbound Mail Received | email.inbound.received | When a new inbound email arrives on a [receiving domain](/email-api/receiving) | ## Payloads Every webhook notification includes an `event_name` or `event` key and a `payload` or `data` key. The payload structure depends on the event type. ### Outbound delivery events ```json theme={null} { "event_name": "api_mail_log_permanent_failure", "payload": { "id": 5555555555, "subject": "Hello from the Paubox Email API", "header_message_id": "<XXX430aa-9b7c-42d5-9614-2e38f5a3f71f@XXXXXXXXX.com>", "source_tracking_id": "XXXef39e-b376-4a44-b2b9-85bdb406dXXX", "outbound_queue_id": "XXXyFY0y3Yz2XXX", "time": "2022-04-18T20:27:25.379Z", "from": "sender@example.com", "to": "recipient@example.com", "custom_headers": { "X-Custom-Header": "value" } } } ``` ### Inbound mail received Each email that arrives on one of your receiving domains produces one `email.inbound.received` event, usually within seconds. Mail classified as spam is included, with `spam: true`. ```json theme={null} { "id": "0192f0c4-7d1e-7a3b-9c1d-5e6f7a8b9c0d", "event_name": "email.inbound.received", "product": "email_api", "occurred_at": "2026-10-01T14:30:01+00:00", "payload": { "event": "email.inbound.received", "data": { "email_id": "01a0f9e7-9f8e-7303-b771-1bccbe704c4a", "envelope": { "from": "sender@example.com", "to": "inbox@yourcompany.inbound.paubox.email" }, "from": [ { "name": "Sender Name", "address": "sender@example.com" } ], "to": [ { "name": null, "address": "inbox@yourcompany.inbound.paubox.email" } ], "cc": [], "subject": "New patient referral", "date": "2026-10-01T14:29:58Z", "received_at": "2026-10-01T14:30:01Z", "message_id": ["abc123@example.com"], "domain": "yourcompany.inbound.paubox.email", "text_body": "Please see the attached referral.", "html_body": "<p>Please see the attached referral.</p>", "attachments": [ { "id": "56b40f62-bca1-5f96-b547-75e46c4c9f21", "filename": "referral.pdf", "content_type": "application/pdf", "size": 52400, "content_id": null, "download_url": "https://api.paubox.com/v1/email/receiving/01a0f9e7-9f8e-7303-b771-1bccbe704c4a/attachments/56b40f62-bca1-5f96-b547-75e46c4c9f21" } ], "size": 58200, "spam": false, "spam_score": 1.2, "authentication": { "spf": "pass", "dkim": "pass", "dmarc": "pass" } } } } ``` **Envelope** | Field | Type | Description | | :- | :- | :- | | `id` | string | Unique ID for this delivery. Retries of the same delivery keep the same ID, which is also sent as the `X-Paubox-Delivery-Id` header | | `event_name` | string | `email.inbound.received` | | `product` | string | `email_api` | | `occurred_at` | string | When Paubox received the email | | `payload.event` | string | `email.inbound.received` | | `payload.data` | object | The email, described below | **Email (`payload.data`)** | Field | Type | Description | | :- | :- | :- | | `email_id` | string | Paubox ID for this email (a UUID). Use it with the [receiving API](/email-api/receiving) and to deduplicate events | | `envelope.from` / `envelope.to` | string | SMTP envelope addresses | | `from`, `to`, `cc` | array of `{name, address}` | Parsed header addresses | | `subject` | string or null | Email subject line | | `date` | string or null | `Date` header from the original message | | `received_at` | string | Timestamp when Paubox received the message | | `message_id` | array of strings or null | `Message-ID` header, parsed into IDs without angle brackets. Normally one element; `null` if the header is missing or can't be parsed | | `domain` | string | The receiving domain | | `text_body` / `html_body` | string or null | Plain text and HTML body content | | `attachments` | array | Attachments, each with `id`, `filename`, `content_type`, `size`, `content_id` and `download_url` (see below) | | `size` | integer | Total message size in bytes | | `spam` | boolean | Whether the message was classified as spam | | `spam_score` | number or null | Spam score (lower is better) | | `authentication` | object | SPF, DKIM, and DMARC results | **Attachments** | Field | Type | Description | | :- | :- | :- | | `id` | string | Paubox ID for this attachment (a UUID) | | `filename` | string or null | File name, if the sender provided one | | `content_type` | string or null | MIME type | | `size` | integer or null | Size in bytes | | `content_id` | string or null | `Content-ID`, for images referenced from the HTML body | | `download_url` | string | Download link. Request it with your API key, like any other Email API call (see [Authentication](/email-api/authentication)). The file is always served as a download | ## Managing webhook endpoints via the API Webhook endpoints for outbound delivery events can be managed programmatically. See the [API reference](/email-api/webhooks/list) for full details. The API doesn't accept `email.inbound.received`; subscribe to it in the [Paubox Dashboard](https://next.paubox.com/emailapi/webhooks). It isn't yet available on every account. If it isn't offered when you add an endpoint, contact Paubox support. ```bash theme={null} curl --request POST \ --url https://api.paubox.com/v1/email/webhook_endpoints \ --header 'Authorization: Bearer YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "target_url": "https://example.com/webhooks/paubox", "events": ["api_mail_log_delivered"], "active": true }' ``` ## Retry behavior **Inbound mail events** are retried when your endpoint responds with `429`, a `5xx` status, takes longer than 30 seconds, or can't be reached. Paubox retries after 30 seconds, 2 minutes and 5 minutes, for up to 4 attempts in total. Any other non-`2xx` response is treated as final and isn't retried. A `410 Gone` response also disables the endpoint. Respond with a `2xx` status once you've accepted the event. Because a retry can follow a request your endpoint did receive, deduplicate on `payload.data.email_id`. **Outbound delivery events:** Paubox does not currently retry failed webhook deliveries. If your endpoint is unavailable when an event fires, that notification will not be re-sent. Design your endpoint to be highly available, and use the [Get message receipt](/email-api/message-receipt) endpoint to poll for status if you need guaranteed delivery tracking. ## Verifying webhook signatures ### Inbound mail events Every inbound mail delivery is signed with your endpoint's signing secret (`whsec_...`), shown once when you create the endpoint. Each request carries two headers: * `X-Paubox-Timestamp`: when the request was signed, in Unix seconds. * `X-Paubox-Signature`: a hex-encoded HMAC-SHA256 of `<timestamp>.<raw request body>`, keyed with the whole signing secret, including the `whsec_` prefix. To verify a request: 1. Read the raw request body before parsing it as JSON. 2. Compute the HMAC-SHA256 of the timestamp, a `.`, and the raw body, using your signing secret as the key. 3. Compare it with `X-Paubox-Signature` using a constant-time comparison. 4. Reject requests whose timestamp is more than a few minutes old. The timestamp is part of the signed content, so a captured request can't be replayed with a fresh one. ```python Python theme={null} import hashlib import hmac import time def verify_paubox_webhook(raw_body: bytes, headers, secret: str) -> bool: timestamp = headers.get("X-Paubox-Timestamp") signature = headers.get("X-Paubox-Signature") if not timestamp or not signature: return False if abs(time.time() - int(timestamp)) > 300: return False signed = timestamp.encode() + b"." + raw_body expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, signature) ``` ```javascript Node.js theme={null} import crypto from "node:crypto"; function verifyPauboxWebhook(rawBody, headers, secret) { const timestamp = headers["x-paubox-timestamp"]; const signature = headers["x-paubox-signature"]; if (!timestamp || !signature) return false; if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false; const expected = crypto .createHmac("sha256", secret) .update(`${timestamp}.${rawBody}`) .digest("hex"); return ( expected.length === signature.length && crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature)) ); } ``` ### Outbound delivery events Outbound delivery events are not signed. To restrict who can reach your endpoint, use network-level controls such as IP allowlisting, and use the [Get message receipt](/email-api/message-receipt) endpoint to confirm a message's status. # Create a webhook endpoint with the Email API Source: https://docs.paubox.com/email-api/webhooks/create openapi1 POST /webhook_endpoints Creates a new webhook endpoint that receives event notifications at the specified URL. # Delete a webhook endpoint with the Email API Source: https://docs.paubox.com/email-api/webhooks/delete openapi1 DELETE /webhook_endpoints/{id} Delete a webhook endpoint by ID. Paubox stops sending event notifications to its target URL. # Get a webhook endpoint with the Email API Source: https://docs.paubox.com/email-api/webhooks/get openapi1 GET /webhook_endpoints/{id} Retrieve a webhook endpoint by ID, including its target URL, subscribed events, and active status. # List webhook endpoints with the Email API Source: https://docs.paubox.com/email-api/webhooks/list openapi1 GET /webhook_endpoints Returns the webhook endpoints for the authenticated account. Without `page` or `items`, returns a JSON array of every endpoint. With either, returns one page as `data` with `page_info`. # Update a webhook endpoint with the Email API Source: https://docs.paubox.com/email-api/webhooks/update openapi1 PATCH /webhook_endpoints/{id} Update a webhook endpoint's target URL or subscribed events, or disable it by setting active to false. Only the fields you send are changed. # Archive a form with the Forms API Source: https://docs.paubox.com/forms/archive-form openapi-forms POST /api/forms/{form_id}/archive Archives a form. Archiving also deactivates the form (sets `active` to false), so the public form endpoint no longer serves it. # Forms API authentication Source: https://docs.paubox.com/forms/authentication Authenticate to the Paubox Forms API with an API key that has the forms scope: find your credentials, pass them in requests, and handle auth errors. The Paubox Forms API has two tiers of endpoints: * **Public respondent endpoints** require no authentication. These are the endpoints called from end user devices when a respondent loads or submits a form: [Get form metadata](/forms/get-form) (`GET /public/form_data/{form_id}`) and [Submit a form response](/forms/submit-form) (`POST /api/forms/{form_id}/submissions`). The form's UUID acts as access control. * **Form management endpoints** require a Paubox API key with the `forms` scope. This covers everything else: listing, creating, updating, copying, archiving, and unarchiving forms, retrieving form statistics, and reading or exporting submissions. ## Find your credentials **1. Generate an API key** API keys are created in the Paubox dashboard. Copy the key when it is displayed; store it somewhere safe. **2. Confirm the key has the forms scope** Paubox API keys are scoped per product. The key must include the `forms` scope to call the Forms API. A key scoped only to other products (for example, the Email API) is rejected with `401 Unauthorized`. **3. Note the base URL** All Forms API requests go to the same base URL: ``` https://api.paubox.com/v1/forms ``` ## Pass credentials in requests Include the `Authorization` header with every form-management API call: ```bash theme={null} curl --request GET \ --url 'https://api.paubox.com/v1/forms/api/forms?customer_id=YOUR_CUSTOMER_ID' \ --header 'Authorization: Bearer YOUR_API_KEY' ``` The Forms API accepts Bearer tokens only: ``` Authorization: Bearer YOUR_API_KEY ``` > [!NOTE] > > The Forms API does not accept the `Token token=` header format used by the Paubox Marketing API. Always use `Bearer`. ## Authentication errors | Status | Meaning | | - | - | | `401 Unauthorized` | The `Authorization` header is missing, the API key is invalid, or the key does not include the `forms` scope. | | `403 Forbidden` | The API key is valid, but the requested resource belongs to a different customer. | ## Key handling * Generate a new key before revoking an old one to avoid downtime. * Revoke keys immediately if they are exposed or a team member with access leaves. > [!WARNING] > > Never commit API keys to source control. Use environment variables or a secrets manager to inject credentials at runtime. > > ```bash theme={null} > # Good > export PAUBOX_API_KEY=your_api_key > curl -H "Authorization: Bearer $PAUBOX_API_KEY" ... > > # Bad: do not do this > curl -H "Authorization: Bearer a5e1ec4aefaa5fef1a9a2a46459eeae3503034a9" ... > ``` # Copy a form with the Forms API Source: https://docs.paubox.com/forms/copy-form openapi-forms POST /api/forms/copy Creates a copy of an existing form with a new title. The copy starts with a submission count of 0 and no vanity URL. Returns the full new form object. # Create a form with the Forms API Source: https://docs.paubox.com/forms/create-form openapi-forms POST /api/forms Creates a new form. Returns the UUID of the created form. A new form is inactive unless the request sets `active: true`, and the public form endpoint returns 404 for it until it is activated. # Export a submission as CSV with the Forms API Source: https://docs.paubox.com/forms/export-submission-csv openapi-forms GET /api/forms/{form_id}/submissions/submission-csv/{submission_id} Exports a single submission as a CSV attachment. The `Content-Disposition` filename is derived from the form's title plus the submission date in Pacific time, e.g. `New-Patient-Intake-2026-08-27.csv`. Uses the same column layout as the full export (a "Created At" column followed by one column per form field), with a single data row. # Export a submission as PDF with the Forms API Source: https://docs.paubox.com/forms/export-submission-pdf openapi-forms GET /api/forms/{form_id}/submissions/{submission_id}/submission-pdf Exports a single submission as a PDF attachment. The `Content-Disposition` filename is derived from the form's title plus the submission date in Pacific time, e.g. `New-Patient-Intake-2026-08-27.pdf`; titles are reduced to alphanumerics, `-` and `_`. For signable forms, the PDF includes the respondent's signature images. # Export submissions as CSV with the Forms API Source: https://docs.paubox.com/forms/export-submissions-csv openapi-forms GET /api/forms/{form_id}/submissions/submission-csv Exports all submissions of a form as a CSV attachment. The `Content-Disposition` filename is derived from the form's title plus the export date in Pacific time, e.g. `New-Patient-Intake-submissions-2026-08-27.csv`. The first column is "Created At", followed by one column per form field, using the field labels from the form definition. # Get form statistics with the Forms API Source: https://docs.paubox.com/forms/form-stats openapi-forms GET /api/forms/stats Returns aggregate form statistics for a customer: the number of active forms, the total submission count, and the number of submissions received in the last 7 days. # Get a public form with the Forms API Source: https://docs.paubox.com/forms/get-form openapi-forms GET /public/form_data/{form_id} Returns the full form definition (HTML, JSON schema, CSS) for a given form. Called by the form embed before rendering a form to a respondent. No authentication required. # Get a form with the Forms API Source: https://docs.paubox.com/forms/get-form-details openapi-forms GET /api/forms/{form_id} Returns the full form definition by ID, including inactive and archived forms (unlike the public endpoint, which only serves renderable forms to respondents). # Get a submission's signature image with the Forms API Source: https://docs.paubox.com/forms/get-submission-signature openapi-forms GET /api/forms/{form_id}/submissions/{submission_id}/signature/{field_name} Returns the signature image captured for a signature field on a submission, as a PNG. The response is sent with `Cache-Control: no-store, private`. # Paubox Forms API Source: https://docs.paubox.com/forms/index Build, host, and process HIPAA compliant forms directly inside your application. The Paubox Forms API lets you build, host, and process HIPAA compliant forms (patient intake, consent, surveys, waivers) directly inside your application. Submissions are stored on Paubox's HITRUST certified infrastructure and visible in your Paubox Forms account. The Forms API is part of Paubox Forms, Paubox's HIPAA compliant intake form product. ## What you can build with it Healthcare teams use the Paubox Forms API to: * Embed patient intake forms inside a portal or app and process responses without storing PHI on their own systems * Collect signed consent forms tied to appointments, onboarding, or treatment plans * Securely collect patient data with HIPAA compliant forms * Create, update, copy, and archive forms programmatically instead of clicking through the Paubox Forms app * Pull submissions into their own systems, or export them as CSV or PDF for records and reporting ## Available endpoints Base URL: `https://api.paubox.com/v1/forms` ### Public endpoints These endpoints are called by respondents loading and submitting forms from end user devices, so they require no API key. | Method | Endpoint | Purpose | API key | | - | - | - | - | | `GET` | `/public/form_data/{form_id}` | Retrieve a form's full definition (HTML, JSON schema, CSS) for rendering to a respondent | No | | `POST` | `/api/forms/{form_id}/submissions` | Submit a form response, including text fields and file attachments | No | See the reference: [Get form metadata](/forms/get-form) and [Submit a form response](/forms/submit-form). ### Management endpoints These endpoints require an API key with the `forms` scope, sent as `Authorization: Bearer YOUR_API_KEY`. See [Authentication](/forms/authentication). | Method | Endpoint | Purpose | API key | | - | - | - | - | | `GET` | `/api/forms` | List your forms, with filtering, search, sorting, and pagination | Yes | | `POST` | `/api/forms` | Create a form | Yes | | `GET` | `/api/forms/{form_id}` | Get a form's full definition, including inactive and archived forms | Yes | | `PUT` | `/api/forms/{form_id}` | Update a form (partial update; omitted fields are unchanged) | Yes | | `POST` | `/api/forms/copy` | Copy an existing form under a new title | Yes | | `POST` | `/api/forms/{form_id}/archive` | Archive a form (also deactivates it) | Yes | | `POST` | `/api/forms/{form_id}/unarchive` | Unarchive a form (does not re-activate it) | Yes | | `GET` | `/api/forms/stats` | Get form statistics for a customer: active form count and submission counts | Yes | | `GET` | `/api/forms/{form_id}/submissions` | List submissions for a form, with sorting and pagination | Yes | | `GET` | `/api/forms/{form_id}/submissions/submission-csv` | Export all submissions of a form as CSV | Yes | | `GET` | `/api/forms/{form_id}/submissions/submission-csv/{submission_id}` | Export a single submission as CSV | Yes | | `GET` | `/api/forms/{form_id}/submissions/{submission_id}/submission-pdf` | Export a single submission as PDF | Yes | | `GET` | `/api/forms/{form_id}/submissions/{submission_id}/signature/{field_name}` | Get the signature image for a submission's signature field, as PNG | Yes | See the reference: [List forms](/forms/list-forms), [Create a form](/forms/create-form), [Get a form](/forms/get-form-details), [Update a form](/forms/update-form), [Copy a form](/forms/copy-form), [Archive a form](/forms/archive-form), [Unarchive a form](/forms/unarchive-form), [Get form statistics](/forms/form-stats), [List form submissions](/forms/list-submissions), [Export submissions as CSV](/forms/export-submissions-csv), [Export a submission as CSV](/forms/export-submission-csv), [Export a submission as PDF](/forms/export-submission-pdf), and [Get a signature image](/forms/get-submission-signature). ## How it handles HIPAA and security The Paubox Forms API runs on the same HIPAA compliant infrastructure as the rest of the Paubox platform. Form definitions and submissions are stored in Paubox's secure environment. Paubox signs a business associate agreement (BAA) with every customer. The two public endpoints are called by respondents loading and submitting forms from end user devices, where authentication wouldn't be feasible. The form's UUID acts as access control: * Form IDs are UUIDs, which makes them difficult to enumerate * Submissions are capped at 250 MB total, including form fields and any file attachments All management endpoints require an API key with the `forms` scope, and a key can only access forms belonging to its own customer account or to a client account it manages as a Paubox partner. Paubox Forms is included with paid Paubox accounts, including Paubox Email Suite. ## Authentication | Endpoint | Authentication | | - | - | | `GET /public/form_data/{form_id}` | Public, no API key required | | `POST /api/forms/{form_id}/submissions` | Public, no API key required | | All management endpoints | `Authorization: Bearer YOUR_API_KEY` with the `forms` scope | The two public endpoints are intentionally unauthenticated. Respondents fill out forms from end user devices, so authentication happens at the form definition layer rather than the request layer. Management endpoints (listing, creating, updating, copying, archiving forms, and reading or exporting submissions) require a scoped API key generated in the Paubox dashboard. The key must carry the `forms` scope; a key without it receives a `401 Unauthorized` response, and a valid key requesting another customer's resources receives `403 Forbidden`. See [Authentication](/forms/authentication) for details. ## Get started 1. Create a form in the Paubox Forms app, or generate an API key with the `forms` scope and create one with `POST /api/forms`. A form created through the API is inactive unless you set `active: true`, and the public form endpoint returns `404` until it is activated. Activate it with `PUT /api/forms/{form_id}` and `active: true`. 2. Copy the form's UUID. This is the `form_id` you'll pass to the endpoints. 3. Use the public endpoints to render the form and accept submissions, and the management endpoints to read and export what comes in. > [card] [Get form metadata](/forms/get-form) > > Retrieve the form's HTML, JSON schema, and CSS for rendering to a respondent. > [card] [Submit a form response](/forms/submit-form) > > Post field values and file attachments to the submissions endpoint. > [card] [Authentication](/forms/authentication) > > Generate a scoped API key and authenticate to the management endpoints. > [card] [List form submissions](/forms/list-submissions) > > Retrieve submissions programmatically, or export them as CSV or PDF. ## FAQs > [accordion] Is the Paubox Forms API HIPAA compliant? > > Yes. Form definitions and submissions are stored on Paubox's HITRUST certified, HIPAA compliant infrastructure. All data is encrypted in transit and at rest, and Paubox signs a business associate agreement (BAA) with every customer. > [accordion] Why don't the public Forms API endpoints require authentication? > > The two public endpoints are called by respondents loading and submitting forms from end user devices, where authentication wouldn't be feasible. The form's UUID acts as access control: each form has a unique UUID generated by Paubox when you create the form. All management endpoints require an API key with the `forms` scope. > [accordion] Can the Paubox Forms API collect signatures? > > Yes. Forms can be marked as signable. The `signable` and `signature_confirmation_label` fields on the form metadata indicate signature behavior, and a signature confirmation is recorded with the submission. PDF exports of submissions include the signature image. > [accordion] Can I include file attachments in a form submission? > > Yes. The `attachments` array on `POST /api/forms/{form_id}/submissions` accepts file objects with a `name` and base64 encoded `content`. The maximum total submission size is 250 MB. > [accordion] Where do form submissions go? > > Submissions are stored in your Paubox Forms account and visible in the app. You can configure email notifications to designated recipients on each submission, retrieve submissions with `GET /api/forms/{form_id}/submissions`, or export them as CSV or PDF. > [accordion] What happens if I send an invalid form\_id? > > Every endpoint that takes a `form_id` returns `404 Not Found` for a form that does not exist. The public form fetch (`GET /public/form_data/{form_id}`) also returns `404` for a form that is inactive or archived. > [accordion] What format do form fields take? > > The `form_data` object on a submission accepts key-value pairs where keys match the field names defined in the form's schema. Retrieve the schema by calling `GET /public/form_data/{form_id}` and reading the `form_json` field. > [accordion] Is there a sandbox for testing the Forms API? > > Test against a form in your Paubox Forms account that you set aside for testing, so test submissions stay out of your real forms' submission lists and counts. ## Community & support > [card] [Q\&A](https://github.com/Paubox/community/discussions/categories/paubox-forms) > > Ask usage questions in the Paubox Community. > [card] [Ideas](https://github.com/Paubox/community/discussions/categories/ideas) > > Propose features and improvements. > [!WARNING] > > Never post PHI, recipient addresses, or message content in public threads. Account, billing, or anything sensitive goes to [support@paubox.com](mailto:support@paubox.com). # List forms with the Forms API Source: https://docs.paubox.com/forms/list-forms openapi-forms GET /api/forms Returns a paginated list of forms belonging to a customer. Supports filtering by form ID, title/description search, and archived/active state, plus ordering and pagination. # List form submissions with the Forms API Source: https://docs.paubox.com/forms/list-submissions openapi-forms GET /api/forms/{form_id}/submissions Returns a paginated list of submissions for a form. Each submission's `form_data` field is a JSON-encoded string of the respondent's answers. # Submit a form response with the Forms API Source: https://docs.paubox.com/forms/submit-form openapi-forms POST /api/forms/{form_id}/submissions Submits a respondent's answers for a form. No authentication required. On success, the service stores the submission, increments the form's submission count, emails recipients (if configured), and returns 201 with no body. Maximum request size is **250 MB** (to support file attachments). # Unarchive a form with the Forms API Source: https://docs.paubox.com/forms/unarchive-form openapi-forms POST /api/forms/{form_id}/unarchive Unarchives a form. This does not re-activate it: `active` stays false until the form is updated with `active: true`. # Update a form with the Forms API Source: https://docs.paubox.com/forms/update-form openapi-forms PUT /api/forms/{form_id} Updates a form. This is a partial update: any fields omitted from the request body are left unchanged. # Go SDK authentication Source: https://docs.paubox.com/go-sdk/authentication Configure Paubox API credentials for the Go SDK with your API key or environment variables, plus Forms client setup and security notes for handling keys. ## Obtain your API key The Email API client requires one credential: * **API key**: a secret token that authenticates your requests It is available in the [Paubox dashboard](https://next.paubox.com) under **API Credentials**. ## Create a client Pass the API key directly to `paubox.New`: ```go theme={null} import ( "os" paubox "github.com/paubox/paubox-go/v2" ) client, err := paubox.New( os.Getenv("PAUBOX_API_KEY"), ) if err != nil { log.Fatal(err) } ``` The SDK sets the `Authorization` header automatically on every request: ``` Authorization: Token token=YOUR_API_KEY ``` ## Environment variables The SDK does not read environment variables automatically; you must read them and pass the value to `paubox.New`. The convention used throughout this documentation is `PAUBOX_API_KEY`. ## Forms client The Forms client (`paubox.NewForms`) takes an API key with the `forms` scope and sends it as `Authorization: Bearer YOUR_API_KEY`. Pass an empty string for a public-only client that can call only `GetPublicForm` and `SubmitForm`: ```go theme={null} fc, err := paubox.NewForms(os.Getenv("PAUBOX_FORMS_API_KEY")) if err != nil { log.Fatal(err) } ``` ## Security notes * Never hard-code credentials in source files. * The SDK never logs request bodies, response bodies, or the `Authorization` header. * Clients are safe to create once and reuse across goroutines for the lifetime of your application. # Go SDK email client Source: https://docs.paubox.com/go-sdk/email-client Full reference for the Paubox Go SDK Email API client: sending messages, batch sending, delivery tracking, dynamic templates, and error handling. ## Creating a client ```go theme={null} client, err := paubox.New(apiKey, ...opts) ``` `paubox.New` accepts optional functional options: | Option | Description | | - | - | | `paubox.WithBaseURL(url)` | Override the API base URL (useful for testing) | | `paubox.WithHTTPClient(c)` | Supply a custom `*http.Client` | | `paubox.WithTimeout(d)` | Set a per-request timeout (default: 30 s) | | `paubox.WithRetry(cfg)` | Configure retry behavior (see below) | | `paubox.WithUserAgent(s)` | Prepend a string to the `User-Agent` header | ### Retry configuration By default the client makes up to 3 attempts (the first request plus 2 retries) for `GET` and `DELETE` requests that fail with `429`, a `5xx` response, or a network error, with exponential backoff between 100 ms and 2 s. `MaxAttempts` counts the first request. ```go theme={null} client, err := paubox.New(apiKey, paubox.WithRetry(paubox.RetryConfig{ MaxAttempts: 4, WaitMin: 200 * time.Millisecond, WaitMax: 5 * time.Second, RetryNonIdempotent: false, // set true to also retry POST/PATCH }), ) ``` ## Send a message ```go theme={null} resp, err := client.SendMessage(ctx, &paubox.SendMessageRequest{ Message: msg, OverrideOpenTracking: true, // optional }) ``` ### Message fields ```go theme={null} paubox.Message{ Recipients: []string{"alice@example.com"}, // required; To recipients CC: []string{"manager@example.com"}, // optional BCC: []string{"audit@example.com"}, // optional Headers: paubox.MessageHeaders{ From: "sender@yourdomain.com", // required Subject: "Your results are ready", // required ReplyTo: "support@yourdomain.com", // optional ListUnsubscribe: "<mailto:unsub@yourdomain.com>", // optional }, Content: paubox.MessageContent{ PlainText: paubox.Ptr("Plain text body."), // at least one required HTML: paubox.Ptr("<p>HTML body.</p>"), }, Attachments: []paubox.Attachment{ { FileName: "report.pdf", ContentType: "application/pdf", Content: base64EncodedBytes, // base64-encoded file content }, }, AllowNonTLS: false, // default false: enforce TLS ForceSecureNotification: true, // optional } ``` The `paubox.Ptr[T]` helper creates a pointer to any value, which is required for optional fields typed as `*T`: ```go theme={null} paubox.Ptr("some string") // returns *string paubox.Ptr(true) // returns *bool ``` ### Response ```go theme={null} type SendMessageResponse struct { SourceTrackingID string CustomHeaders map[string]string Data string } ``` ## Send a batch Send up to 50 messages in a single API call. Each message gets its own tracking ID. ```go theme={null} resp, err := client.SendBatch(ctx, &paubox.SendBatchRequest{ Messages: []paubox.Message{ { Recipients: []string{"alice@example.com"}, Headers: paubox.MessageHeaders{From: "f@yourdomain.com", Subject: "Hi Alice"}, Content: paubox.MessageContent{PlainText: paubox.Ptr("Hello Alice")}, }, { Recipients: []string{"bob@example.com"}, Headers: paubox.MessageHeaders{From: "f@yourdomain.com", Subject: "Hi Bob"}, Content: paubox.MessageContent{PlainText: paubox.Ptr("Hello Bob")}, }, }, }) if err != nil { log.Fatal(err) } for i, msg := range resp.Messages { fmt.Printf("[%d] tracking ID: %s\n", i, msg.SourceTrackingID) } ``` ## Check delivery status ```go theme={null} disp, err := client.GetEmailDisposition(ctx, sourceTrackingID) ``` `disp.Data.Message.MessageDeliveries` is a slice of per-recipient records: ```go theme={null} for _, d := range disp.Data.Message.MessageDeliveries { fmt.Printf("%s → %s\n", d.Recipient, d.Status.DeliveryStatus) } ``` `DeliveryStatus` values are exported as constants such as `paubox.DeliveryStatusDelivered`, `paubox.DeliveryStatusProcessing`, and `paubox.DeliveryStatusHardBounced`. Message-level open and click counts are on `disp.Data.Message` (`TotalOpens`, `DistinctOpens`, `TotalClickCount`, `ClicksPerLink`). Per-recipient open state is `d.Status.OpenedStatus`. ## Dynamic templates Templates use [Handlebars](https://handlebarsjs.com) syntax (`{{variable_name}}`). ### Create a template ```go theme={null} tmpl, err := client.CreateTemplate(ctx, &paubox.CreateTemplateRequest{ Name: "appointment-confirmation", Body: []byte(`<p>Hello {{first_name}}, your appointment is on {{date}} at {{time}}.</p>`), }) ``` ### List templates ```go theme={null} list, err := client.ListTemplates(ctx) for _, t := range list.Templates { fmt.Println(t.ID, t.Name) } ``` ### Get a template ```go theme={null} tmpl, err := client.GetTemplate(ctx, 123) ``` ### Update a template ```go theme={null} tmpl, err := client.UpdateTemplate(ctx, 123, &paubox.UpdateTemplateRequest{ Name: "appointment-confirmation-v2", Body: []byte(`<p>Updated body for {{first_name}}.</p>`), }) ``` ### Delete a template ```go theme={null} _, err = client.DeleteTemplate(ctx, 123) ``` ### Send a templated message ```go theme={null} resp, err := client.SendTemplatedMessage(ctx, &paubox.SendTemplatedMessageRequest{ TemplateName: "appointment-confirmation", TemplateValues: map[string]any{ "first_name": "Jane", "date": "2024-03-15", "time": "2:00 PM", }, Message: paubox.TemplatedMessage{ Recipients: []string{"jane@example.com"}, Headers: paubox.MessageHeaders{ From: "appointments@yourclinic.com", Subject: "Your appointment is confirmed", }, }, }) ``` ## Scheduled send Schedule a message for future delivery, check its status, reschedule, or cancel it. ### Schedule a message ```go theme={null} resp, err := client.ScheduleMessage(ctx, &paubox.ScheduleMessageRequest{ Message: msg, ScheduledAt: time.Now().Add(24 * time.Hour), }) if err != nil { log.Fatal(err) } fmt.Printf("Tracking ID: %s, scheduled for: %s\n", resp.SourceTrackingID, resp.ScheduledAt) ``` `ScheduledAt` must be in the future and within 30 days. ### Get scheduled message status ```go theme={null} status, err := client.GetScheduledMessage(ctx, sourceTrackingID) if err != nil { log.Fatal(err) } fmt.Printf("State: %s, scheduled for: %s\n", status.State, status.ScheduledAt) ``` `ScheduledMessageStatus` fields: | Field | Type | Description | | - | - | - | | `SourceTrackingID` | `string` | Tracking ID | | `ScheduledAt` | `string` | Scheduled delivery time | | `State` | `string` | `pending`, `processing`, `sent`, `failed`, `cancelled` | | `MessageID` | `int` | Internal message ID | | `SentAt` | `*string` | When the message was sent, if applicable | | `CancelledAt` | `*string` | When the message was cancelled, if applicable | | `ErrorMessage` | `*string` | Error details, if delivery failed | ### Reschedule a message ```go theme={null} resp, err := client.RescheduleMessage(ctx, sourceTrackingID, time.Now().Add(48 * time.Hour), ) if err != nil { log.Fatal(err) } fmt.Printf("Rescheduled to: %s\n", resp.ScheduledAt) ``` ### Cancel a scheduled message ```go theme={null} resp, err := client.CancelScheduledMessage(ctx, sourceTrackingID) if err != nil { log.Fatal(err) } fmt.Printf("Cancelled: %s (state: %s)\n", resp.SourceTrackingID, resp.State) ``` ## Error handling All methods return a typed `error`. Use `errors.As` to inspect details and `errors.Is` to match sentinels: ```go theme={null} resp, err := client.SendMessage(ctx, req) if err != nil { // Match a specific condition if errors.Is(err, paubox.ErrUnauthorized) { log.Fatal("invalid API key") } if errors.Is(err, paubox.ErrRateLimit) { log.Fatal("rate limited: back off and retry") } // Inspect the full error var apiErr *paubox.PauboxError if errors.As(err, &apiErr) { fmt.Printf("HTTP %d: %s - %s (request ID: %s)\n", apiErr.StatusCode, apiErr.Title, apiErr.Details, apiErr.RequestID) } log.Fatal(err) } ``` ### Sentinel errors | Sentinel | HTTP status | | - | - | | `paubox.ErrBadRequest` | 400 | | `paubox.ErrUnauthorized` | 401 | | `paubox.ErrForbidden` | 403 | | `paubox.ErrNotFound` | 404 | | `paubox.ErrRateLimit` | 429 | | `paubox.ErrServerError` | 500 | `ErrServerError` matches only status 500. To detect any 5xx, use `errors.As` and check `apiErr.StatusCode >= 500`. # Go SDK forms client Source: https://docs.paubox.com/go-sdk/forms-client Retrieve Paubox Form schemas and submit form responses using the Go SDK. `GetPublicForm` and `SubmitForm` are public and need no credentials. All other Forms methods require an API key with the `forms` scope, sent as `Authorization: Bearer YOUR_API_KEY`. Forms are identified by a UUID that you obtain from the Paubox dashboard. ## Creating a client ```go theme={null} // Public-only client: GetPublicForm and SubmitForm fc, err := paubox.NewForms("") if err != nil { log.Fatal(err) } // Client for every Forms method fc, err = paubox.NewForms(os.Getenv("PAUBOX_FORMS_API_KEY")) if err != nil { log.Fatal(err) } ``` The SDK does not read environment variables itself; `PAUBOX_FORMS_API_KEY` is a convention. On a client without a key, the protected methods return an error without calling the API. Optional configuration is available via `FormsOption` values: | Option | Description | | - | - | | `paubox.WithFormsBaseURL(url)` | Override the Forms API base URL | | `paubox.WithFormsHTTPClient(c)` | Supply a custom `*http.Client` | | `paubox.WithFormsTimeout(d)` | Set a per-request timeout | | `paubox.WithFormsRetry(cfg)` | Configure retry behavior | | `paubox.WithFormsUserAgent(s)` | Prepend to the `User-Agent` header | ## Get a form Retrieve a form's metadata, field schema, and rendered HTML/CSS. `GetPublicForm` works without a key; `GetForm` returns the same `Form` but requires one. ```go theme={null} ctx := context.Background() form, err := fc.GetPublicForm(ctx, "your-form-uuid") if err != nil { log.Fatal(err) } fmt.Println("Form:", form.Title) ``` The `Form` struct includes: | Field | Type | Description | | - | - | - | | `Title` | `string` | Display name of the form | | `FormJSON` | `json.RawMessage` | Field schema, unparsed | | `FormHTML` | `*string` | Rendered HTML for embedding | | `FormCSS` | `*string` | Associated stylesheet | ## Submit a form `SubmitForm` returns only an `error`; `nil` means the submission was accepted. ```go theme={null} err = fc.SubmitForm(ctx, "your-form-uuid", &paubox.SubmitFormRequest{ FormData: map[string]any{ "name": "Jane Smith", "email": "jane@example.com", "dob": "1990-01-15", }, }) if err != nil { log.Fatal(err) } ``` ### Submitting with file attachments Pass the raw file bytes. The SDK base64-encodes them, so do not encode them yourself: ```go theme={null} fileBytes, err := os.ReadFile("consent.pdf") if err != nil { log.Fatal(err) } err = fc.SubmitForm(ctx, "your-form-uuid", &paubox.SubmitFormRequest{ FormData: map[string]any{ "name": "Jane Smith", }, Attachments: []paubox.FormSubmissionAttachment{ { Name: "consent.pdf", Content: fileBytes, }, }, }) ``` The `FormSubmissionAttachment` struct: | Field | Type | Description | | - | - | - | | `Name` | `string` | File name including extension | | `Content` | `[]byte` | Raw file content | ## Manage forms These methods require a client created with a `forms`-scoped API key. | Method | Returns | | - | - | | `ListForms(ctx, *ListFormsParams)` | `*ListFormsResponse` | | `CreateForm(ctx, *CreateFormRequest)` | `*CreateFormResponse` | | `GetForm(ctx, id)` | `*Form` | | `UpdateForm(ctx, id, *UpdateFormRequest)` | `*UpdateFormResponse` | | `ArchiveForm(ctx, id)` / `UnarchiveForm(ctx, id)` | `*FormActionResponse` | | `CopyForm(ctx, *CopyFormRequest)` | `*Form` | | `GetFormStats(ctx, *FormStatsParams)` | `*FormStats` | | `ListFormSubmissions(ctx, formID, *ListFormSubmissionsParams)` | `*ListFormSubmissionsResponse` | | `ExportFormSubmissionsCSV(ctx, formID)` | `[]byte` CSV | | `ExportFormSubmissionCSV(ctx, formID, submissionID)` | `[]byte` CSV | | `ExportFormSubmissionPDF(ctx, formID, submissionID)` | `[]byte` PDF | ```go theme={null} list, err := fc.ListForms(ctx, &paubox.ListFormsParams{ CustomerID: 12345, Active: paubox.Ptr(true), Items: 25, }) if err != nil { log.Fatal(err) } for _, f := range list.Results { fmt.Println(f.ID, f.Title) } ``` # Paubox Go SDK Source: https://docs.paubox.com/go-sdk/index Send HIPAA compliant email and submit Paubox Forms from Go applications using the official Paubox Go SDK. The Paubox Go SDK is the official Go client library for the [Paubox Email API](/email-api) and [Paubox Forms](/forms). It provides a type-safe, idiomatic Go interface for sending encrypted email, managing dynamic templates, tracking delivery, and submitting forms, with no external dependencies. ```bash theme={null} go get github.com/paubox/paubox-go/v2 ``` ## What you can do * Send encrypted, HIPAA compliant email to one or more recipients * Send batches of up to 50 messages in a single API call * Track delivery status and open/click engagement per recipient * Create, update, and delete dynamic Handlebars templates * Send templated messages with per-message variable substitution * Schedule, reschedule, and cancel messages * Retrieve Paubox Form schemas and submit form responses with file attachments * Manage forms, submissions, and exports with a forms-scoped API key * Manage receiving domains and mailboxes, and read inbound email * Manage webhook endpoints * Configure automatic retries with exponential backoff and jitter ## Requirements * **Go** 1.23 or later * No external runtime dependencies; the SDK uses only the Go standard library ## Get started > [card] [Quickstart](/go-sdk/quickstart) > > Create a client and send your first email in minutes. > [card] [Authentication](/go-sdk/authentication) > > Obtain and configure your API key. > [card] [Email client](/go-sdk/email-client) > > Full reference for sending email, managing templates, and tracking delivery. > [card] [Forms client](/go-sdk/forms-client) > > Retrieve form schemas and submit responses. > [card] [Receiving client](/go-sdk/receiving-client) > > Manage receiving domains and mailboxes, and read inbound email. > [card] [Webhook client](/go-sdk/webhook-client) > > Create and manage webhook endpoints. # Go SDK quickstart Source: https://docs.paubox.com/go-sdk/quickstart Install the Paubox Go SDK and send your first HIPAA compliant email in minutes. **1. Install the SDK** Add the SDK to your Go module: ```bash theme={null} go get github.com/paubox/paubox-go/v2 ``` The SDK requires Go 1.23 or later and has no external dependencies. **2. Set your API key** Export your Paubox API key as an environment variable: ```bash theme={null} export PAUBOX_API_KEY="YOUR_API_KEY" ``` To obtain your API key, see [Authentication](/go-sdk/authentication). **3. Send your first email** Create a file `main.go` with the following code: ```go theme={null} package main import ( "context" "fmt" "log" "os" paubox "github.com/paubox/paubox-go/v2" ) func main() { client, err := paubox.New( os.Getenv("PAUBOX_API_KEY"), ) if err != nil { log.Fatal(err) } ctx := context.Background() resp, err := client.SendMessage(ctx, &paubox.SendMessageRequest{ Message: paubox.Message{ Recipients: []string{"recipient@example.com"}, Headers: paubox.MessageHeaders{ From: "sender@yourdomain.com", Subject: "Your first Paubox email", }, Content: paubox.MessageContent{ PlainText: paubox.Ptr("This message was sent with the Paubox Go SDK."), }, }, }) if err != nil { log.Fatal(err) } fmt.Println("Sent. Tracking ID:", resp.SourceTrackingID) } ``` Run it: ```bash theme={null} go run main.go ``` ``` Sent. Tracking ID: abc123-def456-... ``` **4. Check delivery status** Use the tracking ID returned by `SendMessage` to check delivery: ```go theme={null} disp, err := client.GetEmailDisposition(ctx, resp.SourceTrackingID) if err != nil { log.Fatal(err) } for _, d := range disp.Data.Message.MessageDeliveries { fmt.Printf("%s → %s\n", d.Recipient, d.Status.DeliveryStatus) } ``` ``` recipient@example.com → delivered ``` ## Next steps * [Email client](/go-sdk/email-client): send batches, attach files, manage dynamic templates, handle errors * [Forms client](/go-sdk/forms-client): retrieve form schemas and submit responses # Go SDK receiving client Source: https://docs.paubox.com/go-sdk/receiving-client Full reference for the Paubox Go SDK receiving API: managing domains, mailboxes, and retrieving inbound email. The receiving methods are on the same `paubox.Client` you use to send email. ```go theme={null} client, err := paubox.New(apiKey) ``` ## Domains ### List domains ```go theme={null} domains, err := client.ListReceivingDomains(ctx) for _, d := range domains { fmt.Println(d.Domain) } ``` ### Create a domain ```go theme={null} domain, err := client.CreateReceivingDomain(ctx, &paubox.CreateReceivingDomainRequest{ Slug: "support", }) fmt.Println(domain.Domain) // support.inbound.paubox.email ``` ### Get a domain ```go theme={null} domain, err := client.GetReceivingDomain(ctx, 1) ``` ### Delete a domain ```go theme={null} err := client.DeleteReceivingDomain(ctx, 1) ``` ## Mailboxes ### List mailboxes ```go theme={null} mailboxes, err := client.ListMailboxes(ctx, domainID) ``` ### Create a mailbox ```go theme={null} mailbox, err := client.CreateMailbox(ctx, domainID, &paubox.CreateMailboxRequest{ Name: "intake", Password: "SecurePass123!", }) fmt.Println(mailbox.EmailAddress) ``` Set `QuotaBytes` (an `*int64`, for example `paubox.Ptr(int64(1073741824))`) on the request to apply a storage quota. ### Get a mailbox ```go theme={null} mailbox, err := client.GetMailbox(ctx, domainID, mailboxID) ``` ### Delete a mailbox ```go theme={null} err := client.DeleteMailbox(ctx, domainID, mailboxID) ``` ## Emails ### List received emails ```go theme={null} resp, err := client.ListReceivedEmails(ctx, &paubox.ListReceivedEmailsRequest{ Limit: paubox.Ptr(10), }) for _, e := range resp.Emails { fmt.Printf("%s: %s\n", e.EmailID, e.Subject) } // Cursor pagination; resp.HasMore reports whether more results exist next, err := client.ListReceivedEmails(ctx, &paubox.ListReceivedEmailsRequest{ After: paubox.Ptr(resp.Emails[len(resp.Emails)-1].EmailID), }) ``` All `ListReceivedEmailsRequest` fields are optional pointers: `Limit`, `After`, `Before`, `Search`, `Sort`, and `Ascending`. ### Get a received email ```go theme={null} email, err := client.GetReceivedEmail(ctx, emailID) fmt.Println(email.TextBody) ``` ### Download an attachment Pass the attachment's `ID` from `email.Attachments`. Email and attachment IDs are UUIDs. ```go theme={null} att := email.Attachments[0] dl, err := client.DownloadAttachment(ctx, email.EmailID, att.ID) if err != nil { log.Fatal(err) } os.WriteFile(filepath.Base(att.FileName), dl.Content, 0o600) ``` `dl.ContentType` holds the response `Content-Type`. # Go SDK webhook client Source: https://docs.paubox.com/go-sdk/webhook-client Create, list, get, update, and delete Paubox webhook endpoints with the Go SDK to receive Email API and Forms events. > [!NOTE] > > Webhook endpoint methods require SDK 2.0.0 or later. They are on `*paubox.WebhooksClient`, not on the `*paubox.Client` you use to send email. `*paubox.WebhooksClient` manages webhook endpoints through the Paubox webhooks service at `https://api.paubox.com/v1/webhooks`. It sends a scoped API key as `Authorization: Bearer YOUR_API_KEY`. The key's scopes decide which events it can subscribe to. ## Create the client ```go theme={null} import "github.com/paubox/paubox-go/v2" webhooks, err := paubox.NewWebhooks("YOUR_API_KEY") if err != nil { log.Fatal(err) } ``` `NewWebhooks` returns an error if the key is empty. It accepts `WithWebhooksBaseURL`, `WithWebhooksHTTPClient`, `WithWebhooksTimeout`, `WithWebhooksRetry`, and `WithWebhooksUserAgent` options. The client is safe for concurrent use. ## Events | Event | Required scope | Fires when | | - | - | - | | `api_mail_log_delivered` | `email_api` | An Email API message is delivered | | `api_mail_log_opened` | `email_api` | A delivered message is opened | | `api_mail_log_temporary_failure` | `email_api` | Delivery fails temporarily | | `api_mail_log_permanent_failure` | `email_api` | Delivery fails permanently | | `email.inbound.received` | `email_api`, with no sender-domain limit | Inbound mail is received | | `forms.submission.created` | `forms` | A form submission is received | The SDK doesn't check event names. The API returns 422 for an unknown event and 403 for an event the key isn't scoped for. Email API keys created in the Paubox Dashboard are limited to a sender domain, so subscribe to inbound mail in the Paubox Dashboard under [Settings > Webhooks](https://next.paubox.com/settings/webhooks). For payloads and signature verification, see [Webhooks](/email-api/webhooks). ## List webhook endpoints ```go theme={null} list, err := webhooks.ListWebhookEndpoints(ctx, &paubox.ListWebhookEndpointsParams{ Page: paubox.Ptr(1), Items: paubox.Ptr(50), }) if err != nil { return err } for _, ep := range list.Data { fmt.Println(ep.ID, ep.TargetURL, ep.Status) } fmt.Println(list.PageInfo.Count) ``` Pass `nil` for the default page. `PageInfo.Count` is the total number of endpoints, not the length of `Data`. Endpoints carrying an event the key isn't scoped for are left out. ## Create a webhook endpoint ```go theme={null} created, err := webhooks.CreateWebhookEndpoint(ctx, &paubox.CreateWebhookEndpointRequest{ TargetURL: "https://example.com/webhooks/paubox", Events: []string{"api_mail_log_delivered", "api_mail_log_opened"}, }) if err != nil { return err } fmt.Println(created.ID) fmt.Println(created.SigningSecret) ``` `TargetURL` must be an `https` URL that doesn't point at a private or internal address. `CreateWebhookEndpoint` returns a `*paubox.CreatedWebhookEndpoint`, which embeds `paubox.WebhookEndpoint` (`ID`, `TargetURL`, `Status`, `Events`, `CreatedAt`, `UpdatedAt`) and adds `SigningSecret`. The signing secret is returned only by this call; store it when you create the endpoint. To replace a lost secret, delete the endpoint and create a new one. ## Get a webhook endpoint ```go theme={null} endpoint, err := webhooks.GetWebhookEndpoint(ctx, "2ec66c21-bf48-48eb-8d28-f80b2d6b77c7") ``` ## Update a webhook endpoint ```go theme={null} endpoint, err := webhooks.UpdateWebhookEndpoint(ctx, "2ec66c21-bf48-48eb-8d28-f80b2d6b77c7", &paubox.UpdateWebhookEndpointRequest{ Status: paubox.Ptr("disabled"), }) ``` `UpdateWebhookEndpointRequest` has optional `TargetURL`, `Status` (`"active"` or `"disabled"`), and `Events` fields. Only the fields you set are sent. `Events` replaces the endpoint's event list. ## Delete a webhook endpoint ```go theme={null} err := webhooks.DeleteWebhookEndpoint(ctx, "2ec66c21-bf48-48eb-8d28-f80b2d6b77c7") ``` ## Error handling ```go theme={null} var apiErr *paubox.PauboxError if errors.As(err, &apiErr) { fmt.Println(apiErr.StatusCode, apiErr.Title) } ``` A non-2xx response returns a `*paubox.PauboxError`, the same type the email and forms clients return, with the API's error text in `Title`. Creating a second endpoint for the same `TargetURL` returns 422, and an ID that isn't on your account returns 404. An ID that isn't a UUID returns an error before any request is sent. # Java SDK authentication Source: https://docs.paubox.com/java-sdk/authentication Configure Paubox API credentials for the Java SDK with a config.properties file loaded at startup, plus FormsService setup and key security notes. ## Obtain your API key The Email API service requires one credential: * **API key**: a secret token that authenticates your requests It is available in the [Paubox dashboard](https://next.paubox.com) under **API Credentials**. ## Create config.properties Create a `config.properties` file in your project directory: ```properties theme={null} APIKEY=YOUR_API_KEY APIUSER=YOUR_API_USERNAME ``` `EmailService` sends messages and checks delivery status through `https://api.paubox.net/v1/APIUSER/`, so set `APIUSER` to your Paubox API username. `ReceivingService` uses only `APIKEY`. `FormsService` uses `FORMSAPIKEY` instead (see [FormsService](#formsservice)). `WebhookService` uses a scoped API key from `WEBHOOKSAPIKEY` (see [Webhook client](/java-sdk/webhook-client)). ## Load credentials at startup Call `ConfigurationManager.getProperties` once before creating an `EmailService`; the service reads `APIUSER` when it is constructed. Pass the file path relative to your working directory or as an absolute path: ```java theme={null} import com.paubox.config.ConfigurationManager; ConfigurationManager.getProperties("config.properties"); ``` If the file can't be read, `getProperties` prints a stack trace and returns without throwing, and later requests go out without your credentials. The SDK reads `APIKEY` from the loaded properties and sets the `Authorization` header automatically on every request: ``` Authorization: Token token=YOUR_API_KEY ``` ## FormsService `getForm` and `submitForm` are public and need no credentials. All other `FormsService` methods need an API key with the `forms` scope, sent as `Authorization: Bearer YOUR_API_KEY`. Set it as `FORMSAPIKEY` in `config.properties` and load the file before creating the service, or pass it to the constructor: ```java theme={null} import com.paubox.service.FormsService; // Reads FORMSAPIKEY from the loaded config.properties FormsService formsService = new FormsService(); // Or pass the key directly FormsService scopedFormsService = new FormsService("YOUR_API_KEY"); ``` ## Security notes * Do not commit `config.properties` to source control. Add it to `.gitignore`. * In production environments, consider reading credentials from system environment variables and writing them to the properties file at startup rather than storing them statically on disk. # Java SDK email client Source: https://docs.paubox.com/java-sdk/email-client Full reference for the Paubox Java SDK email client: building messages, sending email, tracking delivery, and error handling. ## Instantiation After loading credentials with `ConfigurationManager.getProperties(...)`, create the service: ```java theme={null} import com.paubox.service.EmailService; EmailService service = new EmailService(); ``` ## Building a message Messages are built by setting properties on `Message`, `Header`, and `Content` objects, then wiring them together: ```java theme={null} import com.paubox.data.*; Header header = new Header(); header.setFrom("sender@yourdomain.com"); // required header.setSubject("Your results are ready"); // required header.setReplyTo("support@yourdomain.com"); // optional Content content = new Content(); content.setPlainText("Plain text body."); // at least one required content.setHtmlText("<p>HTML body.</p>"); // optional; auto base64-encoded Message message = new Message(); message.setRecipients(new String[]{"alice@example.com"}); // required message.setHeader(header); message.setContent(content); message.setCc(new String[]{"manager@example.com"}); // optional message.setBcc(new String[]{"audit@example.com"}); // optional message.setAllowNonTLS(false); // optional; default false message.setForceSecureNotification("true"); // optional ``` ### Attachments Base64-encode the file content before setting it on the attachment: ```java theme={null} import java.nio.file.Files; import java.nio.file.Paths; import java.util.Base64; import java.util.ArrayList; byte[] fileBytes = Files.readAllBytes(Paths.get("report.pdf")); String encoded = Base64.getEncoder().encodeToString(fileBytes); Attachment attachment = new Attachment(); attachment.setFileName("report.pdf"); attachment.setContentType("application/pdf"); attachment.setContent(encoded); ArrayList<Attachment> attachments = new ArrayList<>(); attachments.add(attachment); message.setAttachments(attachments); ``` ## Send a message ```java theme={null} SendMessageResponse response = service.sendMessage(message); System.out.println("Tracking ID: " + response.getSourceTrackingId()); ``` The `SendMessageResponse` fields: | Method | Description | | - | - | | `getSourceTrackingId()` | Use to check delivery status | | `getData()` | Raw response data | | `getErrors()` | List of `Error` objects if the request failed | ## Check delivery status ```java theme={null} GetEmailDispositionResponse disposition = service.getEmailDisposition(response.getSourceTrackingId()); for (MessageDeliveries delivery : disposition.getData().getMessage().getMessage_deliveries()) { System.out.println( delivery.getRecipient() + " → " + delivery.getStatus().getDeliveryStatus() ); } ``` Common `deliveryStatus` values: `delivered`, `delivered via secure portal`, `soft bounced`, `hard bounced`, `processing`. Opens are reported separately. In SDK v1.3.1 through v2.0.0, `getEmailDisposition` replaces any `openedStatus` the API sends with `"unopened"`, so `getStatus().getOpenedStatus()` returns `"unopened"` for an opened message and `null` for one that hasn't been opened. To check for an open, test `getStatus().getOpenedTime() != null`. ## Scheduled send Schedule a message for future delivery, check its status, reschedule, or cancel it. ### Schedule a message ```java theme={null} import java.time.Instant; import java.time.temporal.ChronoUnit; String scheduledAt = Instant.now().plus(1, ChronoUnit.DAYS).toString(); ScheduleMessageResponse response = service.scheduleMessage(message, scheduledAt); System.out.println("Tracking ID: " + response.getSourceTrackingId()); System.out.println("Scheduled for: " + response.getScheduledAt()); ``` `scheduledAt` must be an ISO 8601 UTC datetime string in the future and within 30 days. The scheduling response classes have no `errors` field, so if the API rejects the request, the returned object's fields are `null`. ### Get scheduled message status ```java theme={null} ScheduledMessageStatus status = service.getScheduledMessage(sourceTrackingId); System.out.println("State: " + status.getState()); // "pending", "processing", "sent", "failed", "cancelled" System.out.println("Scheduled for: " + status.getScheduledAt()); ``` ### Reschedule a message ```java theme={null} String newTime = Instant.now().plus(2, ChronoUnit.DAYS).toString(); RescheduleResponse response = service.rescheduleMessage(sourceTrackingId, newTime); System.out.println("New time: " + response.getScheduledAt()); ``` ### Cancel a scheduled message ```java theme={null} CancelScheduledResponse response = service.cancelScheduledMessage(sourceTrackingId); System.out.println("State: " + response.getState()); // "cancelled" ``` ## Error handling All `EmailService` methods declare `throws Exception`, but an HTTP error response doesn't throw. The SDK returns the API's error body as the response object, so check `getErrors()` before you use the tracking ID. An exception is thrown only for network failures and for responses the SDK can't read. Use the fully qualified `com.paubox.data.Error`, because `Error` alone is ambiguous with `java.lang.Error`: ```java theme={null} try { SendMessageResponse response = service.sendMessage(message); if (response.getErrors() != null && !response.getErrors().isEmpty()) { for (com.paubox.data.Error error : response.getErrors()) { System.err.println("Error " + error.getCode() + ": " + error.getTitle()); } } else { System.out.println("Sent: " + response.getSourceTrackingId()); } } catch (Exception e) { System.err.println("Send failed: " + e.getMessage()); } ``` # Java SDK forms client Source: https://docs.paubox.com/java-sdk/forms-client Retrieve Paubox Form schemas and submit form responses using the Java SDK. `getForm` and `submitForm` do not require API credentials. The form management methods require an API key with the `forms` scope (see [Manage forms](#manage-forms)). Forms are identified by a UUID that you obtain from the Paubox dashboard. ## Instantiation ```java theme={null} import com.paubox.service.FormsService; FormsService service = new FormsService(); ``` No config loading is required for `getForm` and `submitForm`. ## Get a form Retrieve a form's metadata, field schema, and rendered HTML/CSS: ```java theme={null} import com.paubox.data.Form; Form form = service.getForm("your-form-uuid"); System.out.println("Title: " + form.getTitle()); System.out.println("HTML: " + form.getFormHtml()); ``` Key `Form` getters: | Method | Description | | - | - | | `getTitle()` | Display name of the form | | `getFormJson()` | Parsed field schema | | `getFormHtml()` | Rendered HTML for embedding | | `getFormCss()` | Associated stylesheet | | `isActive()` | Whether the form is accepting submissions | | `getSubmissionCount()` | Number of submissions received | ## Submit a form ```java theme={null} import com.paubox.data.FormSubmissionRequest; import java.util.HashMap; import java.util.Map; Map<String, Object> formData = new HashMap<>(); formData.put("first_name", "Jane"); formData.put("last_name", "Smith"); formData.put("email", "jane@example.com"); FormSubmissionRequest request = new FormSubmissionRequest(); request.setFormData(formData); service.submitForm("your-form-uuid", request); ``` `submitForm` returns `void` on success (HTTP 201) and throws on failure. ### Submitting with file attachments The maximum total request size is 250 MB. ```java theme={null} import com.paubox.data.FormSubmissionAttachment; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Base64; import java.util.ArrayList; import java.util.List; byte[] fileBytes = Files.readAllBytes(Paths.get("consent.pdf")); String encoded = Base64.getEncoder().encodeToString(fileBytes); FormSubmissionAttachment attachment = new FormSubmissionAttachment(); attachment.setName("consent.pdf"); attachment.setContent(encoded); List<FormSubmissionAttachment> attachments = new ArrayList<>(); attachments.add(attachment); FormSubmissionRequest request = new FormSubmissionRequest(); request.setFormData(formData); request.setAttachments(attachments); service.submitForm("your-form-uuid", request); ``` ## Manage forms These methods need a `forms`-scoped API key, sent as `Authorization: Bearer YOUR_API_KEY`. Use `new FormsService("YOUR_API_KEY")`, or set `FORMSAPIKEY` in `config.properties`, load it with `ConfigurationManager.getProperties`, and then call `new FormsService()`. Without a key they throw an `Exception`. | Method | Returns | | - | - | | `listForms(FormListRequest)` | `FormListResponse` | | `createForm(CreateFormRequest)` | `String` ID of the new form | | `getFormById(formId)` | `Form` | | `updateForm(formId, UpdateFormRequest)` | `UpdateFormResponse` | | `archiveForm(formId)` / `unarchiveForm(formId)` | `void` | | `copyForm(formId, newTitle)` | `Form` | | `getFormStats(customerId)` | `FormStats`; pass `null` for the key's customer | | `listFormSubmissions(formId, FormSubmissionListRequest)` | `FormSubmissionListResponse` | | `downloadSubmissionsCsv(formId)` | `byte[]` CSV | | `downloadSubmissionCsv(formId, submissionId)` | `byte[]` CSV | | `downloadSubmissionPdf(formId, submissionId)` | `byte[]` PDF | ```java theme={null} import com.paubox.data.FormListRequest; import com.paubox.data.FormListResponse; FormsService formsAdmin = new FormsService("YOUR_API_KEY"); FormListRequest query = new FormListRequest(); query.setCustomerId(12345); query.setActive(true); query.setItems(25); FormListResponse list = formsAdmin.listForms(query); for (Form f : list.getResults()) { System.out.println(f.getId() + ": " + f.getTitle()); } ``` ## Error handling ```java theme={null} try { Form form = service.getForm("your-form-uuid"); service.submitForm("your-form-uuid", request); } catch (Exception e) { System.err.println("Forms error: " + e.getMessage()); } ``` `getForm` and `submitForm` throw `Exception` on HTTP 400 (bad request) and 404 (form not found). # Paubox Java SDK Source: https://docs.paubox.com/java-sdk/index Send HIPAA compliant email and submit Paubox Forms from Java applications using the official Paubox Java SDK. The Paubox Java SDK is the official Java client library for the [Paubox Email API](/email-api) and [Paubox Forms](/forms). Add the JAR to your project and send encrypted, HIPAA compliant email with a few lines of Java. ## Installation The SDK is not published to Maven Central. The `stable-jar-file/Paubox.Email.API.jar` committed to the repository is version 1.2 from 2019 and only supports sending a message and checking its disposition, so do not use it. Instead, download the `Paubox.Email.API-<version>.jar` asset from the [latest GitHub release](https://github.com/Paubox/paubox-java/releases/latest), or build the JAR from source with Maven: ```bash theme={null} git clone https://github.com/Paubox/paubox-java.git cd paubox-java/Paubox_Java/paubox-java mvn -DskipTests package ``` The build writes `target/Paubox.Email.API.jar`. Add the JAR to your project's classpath. **Eclipse / IntelliJ IDEA:** Right-click your project → Build Path / Dependencies → Add External JARs → select `Paubox.Email.API.jar`. **Maven (local JAR):** ```xml theme={null} <dependency> <groupId>com.paubox</groupId> <artifactId>paubox-email-api</artifactId> <version>1.3.1</version> <scope>system</scope> <systemPath>${project.basedir}/lib/Paubox.Email.API.jar</systemPath> </dependency> ``` Apache HttpClient and Jackson are bundled in the JAR; no additional dependencies are required. ## What you can do * Send encrypted, HIPAA compliant email to one or more recipients * Add CC, BCC, attachments, and HTML or plain-text content * Track delivery status per recipient * Schedule, reschedule, and cancel messages * Retrieve Paubox Form schemas and submit form responses with file attachments * Manage forms, submissions, and exports with a forms-scoped API key * Manage receiving domains and mailboxes, and read inbound email * Manage webhook endpoints ## Requirements * Java 8 or later ## Get started > [card] [Quickstart](/java-sdk/quickstart) > > Add the JAR, configure credentials, and send your first email in minutes. > [card] [Authentication](/java-sdk/authentication) > > Set up your API key in a config.properties file. > [card] [Email client](/java-sdk/email-client) > > Full reference for building messages, sending email, and checking delivery. > [card] [Forms client](/java-sdk/forms-client) > > Retrieve form schemas and submit responses. > [card] [Receiving client](/java-sdk/receiving-client) > > Manage receiving domains and mailboxes, and read inbound email. > [card] [Webhook client](/java-sdk/webhook-client) > > Create and manage webhook endpoints. # Java SDK quickstart Source: https://docs.paubox.com/java-sdk/quickstart Add the Paubox Java SDK and send your first HIPAA compliant email in minutes. **1. Add the JAR** Download `Paubox.Email.API-<version>.jar` from the [latest GitHub release](https://github.com/Paubox/paubox-java/releases/latest), or build it from source, and add it to your project's classpath. Do not use the 2019 JAR in the repository's `stable-jar-file/` directory. See [Installation](/java-sdk#installation) for build, IDE, and Maven instructions. **2. Create config.properties** Create a `config.properties` file in your project: ```properties theme={null} APIKEY=YOUR_API_KEY APIUSER=YOUR_API_USERNAME ``` `EmailService` builds the send and delivery status URLs from `APIUSER`, so set it to your Paubox API username. To obtain your API key, see [Authentication](/java-sdk/authentication). **3. Load credentials and send an email** ```java theme={null} import com.paubox.service.EmailService; import com.paubox.data.*; import com.paubox.config.ConfigurationManager; public class SendEmail { public static void main(String[] args) throws Exception { // Load credentials from config.properties ConfigurationManager.getProperties("config.properties"); // Build the message Header header = new Header(); header.setFrom("sender@yourdomain.com"); header.setSubject("Your first Paubox email"); Content content = new Content(); content.setPlainText("This message was sent with the Paubox Java SDK."); Message message = new Message(); message.setRecipients(new String[]{"recipient@example.com"}); message.setHeader(header); message.setContent(content); // Send EmailService service = new EmailService(); SendMessageResponse response = service.sendMessage(message); System.out.println("Sent. Tracking ID: " + response.getSourceTrackingId()); } } ``` **4. Check delivery status** ```java theme={null} GetEmailDispositionResponse disposition = service.getEmailDisposition(response.getSourceTrackingId()); for (MessageDeliveries delivery : disposition.getData().getMessage().getMessage_deliveries()) { System.out.println(delivery.getRecipient() + " → " + delivery.getStatus().getDeliveryStatus()); } ``` ## Next steps * [Email client](/java-sdk/email-client): CC/BCC, attachments, error handling * [Forms client](/java-sdk/forms-client): retrieve form schemas and submit responses # Java SDK receiving client Source: https://docs.paubox.com/java-sdk/receiving-client Full reference for the Paubox Java SDK receiving API: managing domains, mailboxes, and retrieving inbound email. Receiving endpoints are exposed through the `ReceivingService` class, which uses the same API key authentication as `EmailService`. ```java theme={null} ReceivingService receiving = new ReceivingService(); ``` The API key is read from `config.properties` (`APIKEY`), the same file used by `EmailService`. Methods return the raw JSON response as a `String`. ## Domains ### List domains ```java theme={null} String json = receiving.listReceivingDomains(); ``` ### Create a domain ```java theme={null} String json = receiving.createReceivingDomain("support"); ``` Pass `null` to auto-generate a slug. ### Get a domain ```java theme={null} String json = receiving.getReceivingDomain(1); ``` ### Delete a domain ```java theme={null} String json = receiving.deleteReceivingDomain(1); ``` ## Mailboxes ### List mailboxes ```java theme={null} String json = receiving.listReceivingMailboxes(domainId); ``` ### Create a mailbox ```java theme={null} String json = receiving.createReceivingMailbox(domainId, "intake", "SecurePass123!", null); ``` The fourth argument is `quotaBytes` as a `Long` (pass `null` for no quota). ### Get a mailbox ```java theme={null} String json = receiving.getReceivingMailbox(domainId, mailboxId); ``` ### Delete a mailbox ```java theme={null} String json = receiving.deleteReceivingMailbox(domainId, mailboxId); ``` ## Emails ### List received emails ```java theme={null} String json = receiving.listReceivedEmails(10, null, null); ``` Arguments are `limit`, `after` cursor, and `before` cursor; all are nullable. ### Get a received email ```java theme={null} String json = receiving.getReceivedEmail(emailId); ``` ### Download an attachment ```java theme={null} byte[] data = receiving.getReceivedEmailAttachment(emailId, attachmentId); Files.write(Paths.get("report.pdf"), data); ``` Pass the attachment `id` from the received email's `attachments` array. Returns raw bytes; save them with `java.nio.file.Files.write`. # Java SDK webhook client Source: https://docs.paubox.com/java-sdk/webhook-client Create, list, get, update, and delete Paubox webhook endpoints with the Java SDK to receive Email API and Forms events. > [!NOTE] > > The methods on this page require SDK 2.0.0 or later, where `WebhookService` uses the Paubox webhooks service and a scoped API key. `WebhookService` manages webhook endpoints through the Paubox webhooks service at `https://api.paubox.com/v1/webhooks`. It sends a scoped API key as `Authorization: Bearer YOUR_API_KEY`. The key's scopes decide which events it can subscribe to. ## Create the service ```java theme={null} import com.paubox.service.WebhookInterface; import com.paubox.service.WebhookService; WebhookInterface webhooks = new WebhookService("YOUR_API_KEY"); ``` `new WebhookService()` with no arguments uses `WEBHOOKSAPIKEY` from `config.properties`; load the file with `ConfigurationManager.getProperties` first. `WebhookService` doesn't use `APIKEY`. Every method throws `PauboxWebhooksException` before sending a request if no key is set. ## Events | Event | Required scope | Fires when | | - | - | - | | `api_mail_log_delivered` | `email_api` | An Email API message is delivered | | `api_mail_log_opened` | `email_api` | A delivered message is opened | | `api_mail_log_temporary_failure` | `email_api` | Delivery fails temporarily | | `api_mail_log_permanent_failure` | `email_api` | Delivery fails permanently | | `email.inbound.received` | `email_api`, with no sender-domain limit | Inbound mail is received | | `forms.submission.created` | `forms` | A form submission is received | The SDK doesn't check event names. The API returns 422 for an unknown event and 403 for an event the key isn't scoped for. Email API keys created in the Paubox Dashboard are limited to a sender domain, so subscribe to inbound mail in the Paubox Dashboard under [Settings > Webhooks](https://next.paubox.com/settings/webhooks). For payloads and signature verification, see [Webhooks](/email-api/webhooks). ## List webhook endpoints ```java theme={null} WebhookEndpointListRequest request = new WebhookEndpointListRequest(); request.setPage(1); request.setItems(50); WebhookEndpointListResponse result = webhooks.listWebhookEndpoints(request); for (WebhookEndpoint endpoint : result.getData()) { System.out.println(endpoint.getId() + " " + endpoint.getTargetUrl() + " " + endpoint.getStatus()); } System.out.println(result.getPageInfo().getCount()); ``` `listWebhookEndpoints()` with no arguments returns the first page. `getPageInfo().getCount()` is the total number of endpoints, not the length of this page. Endpoints carrying an event the key isn't scoped for are left out. ## Create a webhook endpoint ```java theme={null} CreatedWebhookEndpoint created = webhooks.createWebhookEndpoint( new CreateWebhookEndpointRequest( "https://example.com/webhooks/paubox", Arrays.asList("api_mail_log_delivered", "api_mail_log_opened"))); System.out.println(created.getId()); System.out.println(created.getSigningSecret()); ``` The target URL must be an `https` URL that doesn't point at a private or internal address. `WebhookEndpoint` has `getId()` (a UUID), `getTargetUrl()`, `getStatus()` (`active` or `disabled`), `getEvents()`, `getCreatedAt()`, and `getUpdatedAt()`. `CreatedWebhookEndpoint` extends it with `getSigningSecret()`, which is returned only by this call; store it when you create the endpoint. To replace a lost secret, delete the endpoint and create a new one. ## Get a webhook endpoint ```java theme={null} WebhookEndpoint endpoint = webhooks.getWebhookEndpoint("2ec66c21-bf48-48eb-8d28-f80b2d6b77c7"); ``` ## Update a webhook endpoint ```java theme={null} UpdateWebhookEndpointRequest update = new UpdateWebhookEndpointRequest(); update.setStatus("disabled"); WebhookEndpoint updated = webhooks.updateWebhookEndpoint("2ec66c21-bf48-48eb-8d28-f80b2d6b77c7", update); ``` `UpdateWebhookEndpointRequest` has `setTargetUrl`, `setStatus` (`"active"` or `"disabled"`), and `setEvents`. Only the fields you set are sent. `setEvents` replaces the endpoint's event list. ## Delete a webhook endpoint ```java theme={null} webhooks.deleteWebhookEndpoint("2ec66c21-bf48-48eb-8d28-f80b2d6b77c7"); ``` ## Error handling ```java theme={null} import com.paubox.common.PauboxWebhooksException; try { webhooks.createWebhookEndpoint(new CreateWebhookEndpointRequest( "https://example.com/webhooks/paubox", Arrays.asList("api_mail_log_delivered"))); } catch (PauboxWebhooksException e) { System.out.println(e.getStatusCode()); System.out.println(e.getMessage()); System.out.println(e.getResponseBody()); } ``` A non-2xx response throws `PauboxWebhooksException`, which provides `getStatusCode()`, `getUrl()`, and `getResponseBody()`; its message includes the API's error text. Creating a second endpoint for the same target URL returns 422, and an ID that isn't on your account returns 404. An ID that isn't a UUID throws before any request is sent, with `getStatusCode()` of 0. Every method is declared `throws Exception`, so call it from a method that declares or handles `Exception`. Network failures throw `IOException`, not `PauboxWebhooksException`. The data classes are in `com.paubox.data`. # Overview Source: https://docs.paubox.com/marketing Base URL, authentication, core concepts, and conventions for the Paubox Marketing API. ## Base URL `https://api.paubox.com/v1/marketing` ## Authorization Include an `Authorization` header with every request: `Authorization: Token token=YOUR_API_KEY` Replace `YOUR_API_KEY` with your API key. Create one under [Settings > API Keys](https://next.paubox.com/settings/api_keys): press **Add API Key** and choose the **Paubox Marketing** scope. Each key is displayed only once, when it is created. ## Example call ```bash theme={null} curl -X POST \ https://api.paubox.com/v1/marketing/subscribers \ -H 'Authorization: Token token=YOUR_API_KEY' \ -H 'Content-Type: application/json' \ -d '{ "subscriber": { "email": "recipient@example.com", "first_name": "Jane", "last_name": "Smith" } }' ``` ## Core concepts Four resources cover most of what the Marketing API does. Understanding how they relate makes the rest of the reference easier to navigate. | Resource | What it is | | - | - | | **Campaign mailing** | The email itself — subject, HTML body, text body. Creating one only stores content; it sends nothing. | | **Subscriber** | A person in your account, identified by email address. | | **List** | Who receives a campaign. Either a *subscription list* (explicit membership) or a *dynamic list* (membership computed from saved filters). | | **Subscription** | The link between one subscriber and one list. This is where a list-level opt-out is recorded. | A **send** ties them together: it takes one campaign mailing, one list (or an explicit set of recipient addresses), and delivers the mailing to that audience. The same mailing can be sent more than once, and each send is tracked separately in analytics. > [!NOTE] > > **Subscription lists vs. dynamic lists:** > > Membership in a subscription list is explicit — you add and remove subscribers yourself. Membership in a dynamic list is derived from filters saved on the list, so it changes as your subscriber data changes. Endpoints that act on a list in bulk come in two variants for this reason: `bulk_global_*` for subscription lists, `dynamic_bulk_*` for dynamic lists. ## Send a campaign **1. Create the campaign mailing** [Create a campaign](/marketing/campaigns/create) with your subject and content. `subject` is required and must be unique within your account. ```bash theme={null} curl -X POST \ https://api.paubox.com/v1/marketing/campaign_mailings \ -H 'Authorization: Token token=YOUR_API_KEY' \ -H 'Content-Type: application/json' \ -d '{ "campaign_mailing": { "subject": "March newsletter", "html_part": "<html><body><div>Hello</div></body></html>", "text_part": "Hello", "template_type": "html" } }' ``` The response contains the new mailing's ID, which you will need for every step that follows: ```json theme={null} { "data": { "id": "123e4567-e89b-12d3-a456-426614174000" } } ``` An unsubscribe footer is appended to `html_part` automatically, so you do not need to add one yourself. **2. Preview it** [Send a test email](/marketing/campaigns/send-test-email) to a single address to check rendering before you send to a list. The subject is prefixed with `[Test]`, and test sends are not recorded in analytics. ```bash theme={null} curl -X GET \ 'https://api.paubox.com/v1/marketing/campaign_mailings/123e4567-e89b-12d3-a456-426614174000/send_test_email?to_email=me@example.com' \ -H 'Authorization: Token token=YOUR_API_KEY' ``` A successful test send returns `204 No Content` with an empty body. **3. Revise if needed** [Update the campaign](/marketing/campaigns/update) to change any field. Only the fields you send are modified. **4. Send or schedule** [Send the campaign](/marketing/campaigns/send) to go out now, or [schedule it](/marketing/campaigns/schedule) for a future time. Both take the campaign mailing ID, a `sender_email`, a `from_email`, and exactly one target list, either a `subscription_list_id` or a `dynamic_list_id`. There is no default From address, so always supply `from_email`. Optional `recipient_emails` also receive a copy, which is not tracked in analytics. > [!NOTE] > > **Sending is asynchronous.** > > A successful response means the send was accepted and queued, not that delivery has finished. The list and From address are checked when the queued job runs, so a send with no list, both lists, or no From address still returns a success response and then sends nothing. Track progress through the [campaign analytics](/marketing/analytics/campaigns) endpoints rather than the send response. **5. Measure** Use the analytics endpoints to see how the campaign performed: [send totals](/marketing/analytics/campaigns), [per-send results](/marketing/analytics/campaign-sends), [individual deliveries](/marketing/analytics/deliveries), and [tracking link engagement](/marketing/analytics/tracking-links). > [!TIP] > > **Tip:** > > A brand-new Paubox Marketing account may be temporarily prevented from scheduling its first campaign as an anti-abuse measure. If you hit a `403` with a message about new accounts, wait and try again: the restriction lifts on its own within 24 hours of the account being created. The error message mentions contacting support, but there is no manual override. ## Manage opt-ins and opt-outs Paubox Marketing records two independent levels of opt-out, and it matters which one you use. | Level | Where it lives | Effect | | - | - | - | | **List-level** | `unsubscribed_at` on the subscription | The subscriber stops receiving campaigns sent to that one list. They still receive campaigns sent to other lists. | | **Global** | `opted_out_on` on the subscriber | The subscriber receives nothing, across every list. | Which one an endpoint applies depends on whether you send `subscription_list_ids`: * [`POST /subscriptions/unsubscribe`](/marketing/subscriptions/unsubscribe) **with** `subscription_list_ids` records a list-level opt-out. * The same endpoint **without** `subscription_list_ids` records a global opt-out. * [`POST /subscriptions/subscribe`](/marketing/subscriptions/subscribe) always clears the global opt-out, because a subscriber who is subscribed to any list is by definition not globally unsubscribed. > [!WARNING] > > Treat a global opt-out as permanent unless the recipient asks to be resubscribed. Re-subscribing someone who opted out, without a new request from them, is exactly the pattern that damages sending reputation and can put you out of compliance with anti-spam rules. For a single subscriber and list you already have a subscription record for, [deleting the subscription](/marketing/subscriptions/delete) is the most direct route — it stamps `unsubscribed_at` and leaves everything else untouched. ### Acting on a whole list When you want to opt out an entire list rather than a known set of subscribers, use the bulk endpoints. They accept a `from_subscription_list_id` and operate on everyone in that list, minus any `except_ids` you supply — useful for "select all except these" flows. * Subscription lists: [bulk global subscribe](/marketing/subscriptions/bulk-global-subscribe) and [bulk global unsubscribe](/marketing/subscriptions/bulk-global-unsubscribe) * Dynamic lists: [bulk subscribe](/marketing/subscriptions/dynamic-bulk-subscribe) and [bulk unsubscribe](/marketing/subscriptions/dynamic-bulk-unsubscribe) These endpoints run in the background. See [Background jobs](#background-jobs) below. ## API conventions ### Identifiers Records are identified by UUID. A `campaign_mailing_id`, `subscription_list_id`, or subscriber ID in a URL or request body is always the UUID form: ``` 123e4567-e89b-12d3-a456-426614174000 ``` See [Locating parameter values](/marketing/parameter-values) for where to find each one in the dashboard. > [!NOTE] > > **One exception:** > > [`POST /subscriptions`](/marketing/subscriptions/create) takes the subscriber's internal numeric ID rather than the UUID. To add a subscriber to a list using the UUID you already have, [create the subscriber](/marketing/subscribers/create) with a `subscription_list_id` instead, or use [`POST /subscriptions/subscribe`](/marketing/subscriptions/subscribe). ### Response shapes Most read endpoints return resources in JSON:API form — an `id`, a `type`, and the fields nested under `attributes`: ```json theme={null} { "data": { "id": "123e4567-e89b-12d3-a456-426614174000", "type": "campaign_mailing", "attributes": { "subject": "March newsletter", "created_at": "2026-03-01T12:00:00Z" } } } ``` Write endpoints are terser. Creating or updating a campaign mailing returns only the ID, not the full record: ```json theme={null} { "data": { "id": "123e4567-e89b-12d3-a456-426614174000" } } ``` List and detail responses for the same resource do not always carry the same fields. Listing campaign mailings includes aggregate counts (`sent_count`, `delivered_count`, and so on) but omits the content; fetching a single one includes `html_part`, `text_part`, and `form_data` but omits the counts. Each reference page documents its own response. ### Errors > [!WARNING] > > **Check the response body, not just the status code.** > > Several Marketing API write endpoints return `200 OK` when a request fails validation, with the problem reported in an `errors` key instead of `data`. A client that branches only on HTTP status will treat these as successes. A failed write looks like this: ```json theme={null} { "errors": ["Subject has already been taken"] } ``` Endpoints that behave this way include [creating](/marketing/campaigns/create) and [updating](/marketing/campaigns/update) a campaign mailing, [creating a subscription](/marketing/subscriptions/create), and [updating a drip campaign](/marketing/drip-campaigns/update). The [subscribe](/marketing/subscriptions/subscribe) and [unsubscribe](/marketing/subscriptions/unsubscribe) endpoints also return `200` on failure, with `errors` as a single error-message string rather than an array. [Creating](/marketing/subscribers/create) or [updating](/marketing/subscribers/update) a subscriber and [creating](/marketing/lists/create) or [updating](/marketing/lists/update) a list also return `200`, with `errors` as an object keyed by field: ```json theme={null} { "errors": { "email": ["already exists"] } } ``` Treat the presence of `errors` as the failure signal, and fall back to the status code for authentication (`401`), missing records (`404`), and server errors (`500`). Authentication failures use this shape: ```json theme={null} { "errors": [{ "message": "401 Unauthorized" }] } ``` ### Pagination Pagination differs by endpoint: | Endpoint | Behavior | | - | - | | [`GET /campaign_mailings`](/marketing/campaigns) | Paginated by default with `items` and `page`. Set `pagination=false` to return every mailing in one response. Metadata is in the response headers. | | [`GET /tracking_links`](/marketing/tracking-links) | Paginated with `items` and `page`. Metadata is in the response headers. | | [`GET /subscribers`](/marketing/subscribers) | Paginated with `items` and `page`. The total number of matches is returned as `total_count` in the response body. | | [`GET /subscription_lists`](/marketing/lists) | Not paginated unless you pass `use_pagination=true`, which enables `items` and `page` and adds a `page_info` object to the response body. | Other list endpoints, including drip campaigns, subscriptions and the analytics endpoints, return every record in one response. ### Background jobs Operations that can affect a large number of records do not run inline. Instead they queue a job and return its identifier immediately: ```json theme={null} { "data": { "jid": "a1b2c3d4e5f6a7b8c9d0e1f2" } } ``` A `jid` in the response means the work was accepted, not that it has finished. Bulk subscribe and unsubscribe across a whole list behave this way; supplying an explicit `subscriber_ids` array to those same endpoints processes the change inline and returns the affected subscribers instead. ### Dates Dates are passed as ISO8601 strings with UTC timezone. ## Finding id parameters for subscription\_list\_id, campaign\_mailing\_id, etc. > [card] [Finding parameter values in the web dashboard](/marketing/parameter-values) ## Community & support > [card] [Q\&A](https://github.com/Paubox/community/discussions/categories/paubox-marketing) > > Ask usage questions in the Paubox Community. > [card] [Ideas](https://github.com/Paubox/community/discussions/categories/ideas) > > Propose features and improvements. > [!WARNING] > > Never post PHI, recipient addresses, or message content in public threads. Account, billing, or anything sensitive goes to [support@paubox.com](mailto:support@paubox.com). # Get campaign sends with the Marketing API Source: https://docs.paubox.com/marketing/analytics/campaign-sends openapi2 GET /analytics/campaign_mailing_sends_table Return json data information about campaigns sent # Get campaign analytics with the Marketing API Source: https://docs.paubox.com/marketing/analytics/campaigns openapi2 GET /analytics/campaign_mailing_send_totals Return json data statistics about campaigns sent # Get campaign deliveries with the Marketing API Source: https://docs.paubox.com/marketing/analytics/deliveries openapi2 GET /analytics/campaign_mailing_deliveries_table Returns json data about campaign deliveries sent # Get subscribers by tracking link with the Marketing API Source: https://docs.paubox.com/marketing/analytics/subscribers-by-link openapi2 GET /analytics/subscribers_by_tracking_link Returns json data about subscribers for a specific tracking link # Get tracking link interactions with the Marketing API Source: https://docs.paubox.com/marketing/analytics/tracking-links openapi2 GET /analytics/tracking_links_by_unique_link Returns json data about interactions with tracking links # List campaign mailings with the Marketing API Source: https://docs.paubox.com/marketing/campaigns openapi2 GET /campaign_mailings Return json data about Paubox Marketing Campaign Emails # Bulk delete campaigns with the Marketing API Source: https://docs.paubox.com/marketing/campaigns/bulk-delete openapi2 DELETE /campaign_mailings_bulk_delete Permanently deletes the campaign mailings identified by `campaign_mailing_ids`. There is no single-delete endpoint; delete one mailing by passing an array of one ID. This is irreversible. Only the mailings themselves are deleted; send and delivery records already created for them are kept. Omitting `campaign_mailing_ids` is a no-op and still returns `200` with an empty object. **Example curl command:** ```bash curl -X DELETE \ https://api.paubox.com/v1/marketing/campaign_mailings_bulk_delete \ -H 'authorization: Token token=YOUR_API_KEY' \ -H 'content-type: application/json' \ -d '{ "campaign_mailing_ids": ["123e4567-e89b-12d3-a456-426614174000"] }' ``` # Create a campaign with the Marketing API Source: https://docs.paubox.com/marketing/campaigns/create openapi2 POST /campaign_mailings Creates a campaign mailing (a marketing email) for the authenticated customer. Creating a mailing only stores the content; use [send a campaign](/marketing/campaigns/send) or [schedule a campaign](/marketing/campaigns/schedule) to deliver it. `subject` is required and must be unique within your account. An unsubscribe footer is appended to `html_part` automatically on save. **Example curl command:** ```bash curl -X POST \ https://api.paubox.com/v1/marketing/campaign_mailings \ -H 'authorization: Token token=YOUR_API_KEY' \ -H 'content-type: application/json' \ -d '{ "campaign_mailing": { "subject": "March newsletter", "html_part": "<html><body><div>Hello</div></body></html>", "text_part": "Hello", "template_type": "html" } }' ``` # Get a campaign with the Marketing API Source: https://docs.paubox.com/marketing/campaigns/get openapi2 GET /campaign_mailings/{campaign_mailing_id} Returns a single campaign mailing, including its content. Unlike the list endpoint, this response carries `html_part`, `text_part` and `form_data`, and omits the aggregate delivery counts. # Schedule a campaign mailing with the Marketing API Source: https://docs.paubox.com/marketing/campaigns/schedule openapi2 POST /campaign_mailing_schedule Schedules a new email campaign mailing with specified details for delivery at a future time. Supply exactly one of `subscription_list_id` or `dynamic_list_id`. The list and From address are checked when the scheduled send runs, not when you call this endpoint. If the request has no list, both lists, no `sender_email`, or no From address, the response is still `200` and nothing is sent at `send_at`. A new Paubox Marketing account cannot schedule a campaign for a short time after it is created; during that window this endpoint returns `403`. # Send a campaign mailing with the Marketing API Source: https://docs.paubox.com/marketing/campaigns/send openapi2 POST /campaign_mailing_sends Send campaign email to recipients. Create the email message with [create a campaign](/marketing/campaigns/create) or in the Paubox Marketing web interface. Supply exactly one of `subscription_list_id` or `dynamic_list_id`, and always supply `from_email`: there is no default From address. The send is queued and the response returns before it is checked. If the request has no list, both lists, no `sender_email`, or no From address, the response is still `200` with an empty object and nothing is sent. Confirm the send through [campaign analytics](/marketing/analytics/campaigns). **Note:** The campaign_mailing_id can be retrieved from the id= part of the URL when editing a marketing email. The subscription_list_id can be retrieved from the listId= part of the URL of any Contact List page. # Send a test email with the Marketing API Source: https://docs.paubox.com/marketing/campaigns/send-test-email openapi2 GET /campaign_mailings/{campaign_mailing_id}/send_test_email Sends a one-off preview of the campaign mailing to a single address, so you can check rendering before sending to a list. The subject is prefixed with `[Test]`, and the message is sent from your account's default brand `from_email` and `from_name`. Test sends are not recorded as a campaign send and do not appear in analytics. **Example curl command:** ```bash curl -X GET \ 'https://api.paubox.com/v1/marketing/campaign_mailings/123e4567-e89b-12d3-a456-426614174000/send_test_email?to_email=me@example.com' \ -H 'authorization: Token token=YOUR_API_KEY' ``` # Update a campaign with the Marketing API Source: https://docs.paubox.com/marketing/campaigns/update openapi2 PATCH /campaign_mailings/{campaign_mailing_id} Updates a campaign mailing. Only the fields you send are changed. `PUT` is accepted as an equivalent to `PATCH`. `subject` must stay unique within your account. The unsubscribe footer is reapplied to `html_part` on every save. **Example curl command:** ```bash curl -X PATCH \ https://api.paubox.com/v1/marketing/campaign_mailings/123e4567-e89b-12d3-a456-426614174000 \ -H 'authorization: Token token=YOUR_API_KEY' \ -H 'content-type: application/json' \ -d '{ "campaign_mailing": { "subject": "March newsletter (revised)" } }' ``` # List drip campaigns with the Marketing API Source: https://docs.paubox.com/marketing/drip-campaigns openapi2 GET /drip_campaigns Return json data about Drip Campaigns # Get a drip campaign with the Marketing API Source: https://docs.paubox.com/marketing/drip-campaigns/get openapi2 GET /drip_campaigns/{id} Returns json data about a drip campaign # Pause a drip campaign with the Marketing API Source: https://docs.paubox.com/marketing/drip-campaigns/pause openapi2 POST /drip_campaigns/{id}/pause Pauses a drip campaign # Start a drip campaign with the Marketing API Source: https://docs.paubox.com/marketing/drip-campaigns/start openapi2 POST /drip_campaigns/{id}/start Starts a drip campaign that is in the `drafting` or `pausing` state. Starting a `drafting` campaign queues it to be built, and the response returns `state: building`; the campaign moves to `started` when the build finishes. Resuming a `pausing` campaign returns `state: started`. A `drafting` campaign with no nodes cannot be built. The response is then still `200`, with `{"errors": "Drip campaign must be built to start"}` instead of `data`. Calling this endpoint for a campaign in any other state returns `500`. # Update a drip campaign with the Marketing API Source: https://docs.paubox.com/marketing/drip-campaigns/update openapi2 PUT /drip_campaigns/{id} Updates drip campaign attributes # List subscription lists with the Marketing API Source: https://docs.paubox.com/marketing/lists openapi2 GET /subscription_lists Return json data about subscription lists # Create a subscription list with the Marketing API Source: https://docs.paubox.com/marketing/lists/create openapi2 POST /subscription_lists Creates a subscription list record # Delete a subscription list with the Marketing API Source: https://docs.paubox.com/marketing/lists/delete openapi2 DELETE /subscription_lists/{subscription_list_id} Deletes a subscription list. The subscribers on it are removed from the list but not deleted, and every drip campaign that uses the list is set to `completed`. **Note:** The default (all contacts) list cannot be deleted. A request to delete it returns `200` with an empty object and changes nothing. # Update a subscription list with the Marketing API Source: https://docs.paubox.com/marketing/lists/update openapi2 PATCH /subscription_lists/{subscription_list_id} Updates a subscription list record # Locating parameter values Source: https://docs.paubox.com/marketing/parameter-values How to find parameter values like campaign_mailing_id, subscription_list_id, and campaign_mailing_send_id in the Paubox Marketing web dashboard. Some Marketing API endpoints require IDs that identify specific campaigns, subscription lists, or campaign sends. This page shows where to find each of those IDs in the Paubox Marketing dashboard. > [!TIP] > > All IDs can also be retrieved programmatically. Campaign mailings, subscription lists, and send records all include their `id` in API responses. ## campaign\_mailing\_id A `campaign_mailing_id` uniquely identifies a marketing email (campaign mailing) in Paubox Marketing. It is required when [sending a campaign](/marketing/campaigns/send) or [scheduling a campaign](/marketing/campaigns/schedule), and is accepted as an optional filter on the [campaign deliveries table](/marketing/analytics/deliveries). **To find your `campaign_mailing_id`:** 1. Log in to the Paubox Marketing dashboard. 2. Navigate to **Marketing Emails** (Campaigns). 3. Open or edit any campaign. 4. Copy the value of the `id=` parameter from your browser's address bar. ![Campaign Mailing Id](https://mintcdn.com/paubox-102d0408/8fO92Phey7-8CHbb/images/campaign_mailing_id.png?fit=max\&auto=format\&n=8fO92Phey7-8CHbb\&q=85\&s=c057bec08c625f0191e482f6831b9229) The campaign\_mailing\_id appears as the id= value in the URL when editing a campaign. ## subscription\_list\_id A `subscription_list_id` uniquely identifies a subscription list. It is used when [creating subscribers](/marketing/subscribers/create), [listing subscribers](/marketing/subscribers), [bulk-deleting subscribers](/marketing/subscribers/bulk-delete), [sending](/marketing/campaigns/send) or [scheduling](/marketing/campaigns/schedule) a campaign to a specific list, [updating](/marketing/lists/update) or [deleting a list](/marketing/lists/delete), and [updating a drip campaign](/marketing/drip-campaigns/update). **To find your `subscription_list_id`:** 1. Log in to the Paubox Marketing dashboard. 2. Navigate to **Lists**. 3. Open or edit any list. 4. Copy the UUID from your browser's address bar. ![Subscription List Id 2](https://mintcdn.com/paubox-102d0408/8fO92Phey7-8CHbb/images/subscription_list_id-2.png?fit=max\&auto=format\&n=8fO92Phey7-8CHbb\&q=85\&s=3e89a75e7f14b321d6ae2c2d9d9823ad) The subscription\_list\_id appears in the URL when viewing or editing a subscription list. ## campaign\_mailing\_send\_id A `campaign_mailing_send_id` uniquely identifies a specific send of a campaign. It is required for [tracking links by unique link](/marketing/analytics/tracking-links) and [subscribers by tracking link](/marketing/analytics/subscribers-by-link). It is accepted as the optional `id` filter on [campaign analytics](/marketing/analytics/campaigns), and as an optional filter on the [campaign deliveries table](/marketing/analytics/deliveries) and when [listing tracking links](/marketing/tracking-links). **To find your `campaign_mailing_send_id`:** 1. Log in to the Paubox Marketing dashboard. 2. Navigate to **Analytics**. 3. Click a sent campaign to expand it, then click **Show More Analytics**. 4. Copy the value of the `campaignId=` parameter from your browser's address bar. # List subscribers with the Marketing API Source: https://docs.paubox.com/marketing/subscribers openapi2 GET /subscribers Return json data about subscribers # Bulk create subscribers with the Marketing API Source: https://docs.paubox.com/marketing/subscribers/bulk-create openapi2 POST /subscribers_bulk_create Creates one or more subscriber records. Adds to subscription list if specified, otherwise adds to all contacts. Subscribers are created in the background; the response returns the job ID (`jid`), not a count. If `subscribers` is empty or missing, the response is an empty object. # Bulk delete subscribers with the Marketing API Source: https://docs.paubox.com/marketing/subscribers/bulk-delete openapi2 DELETE /subscribers_bulk_delete Deletes one or more subscriber records. Removes from subscription list if specified, otherwise removed from all contacts. **Warning:** if `subscriber_ids` is omitted or empty, every subscriber in the list is removed, not none. With no `subscription_list_id`, that deletes every subscriber in your account. The bulk removal runs in the background and returns a job ID (`jid`). When `subscriber_ids` is supplied, the response reports `records_deleted` instead. **Example:** ``` DELETE /subscribers_bulk_delete?subscriber_ids=id1,id2,id3&subscription_list_id=list123 ``` # Create a subscriber with the Marketing API Source: https://docs.paubox.com/marketing/subscribers/create openapi2 POST /subscribers Creates a subscriber record. Adds record to subscription list if specified otherwise adds to all contacts. **Example curl command:** ```bash curl -X POST \ https://api.paubox.com/v1/marketing/subscribers \ -H 'authorization: Token token=YOUR_API_KEY' \ -H 'content-type: application/json' \ -d '{ "subscriber": { "email": "test@example.com", "first_name": "test", "last_name": "example" } }' ``` # Get a subscriber with the Marketing API Source: https://docs.paubox.com/marketing/subscribers/get openapi2 GET /subscribers/{subscriber_id} Return json data about subscriber. If no subscriber matches `subscriber_id`, the response is `200` with `{"data": null}`. # Update a subscriber with the Marketing API Source: https://docs.paubox.com/marketing/subscribers/update openapi2 PUT /subscribers/{subscriber_id} Updates a subscriber record # List subscriptions with the Marketing API Source: https://docs.paubox.com/marketing/subscriptions openapi2 GET /subscriptions Returns the subscriptions on the authenticated customer's subscription lists. A subscription is the join between a subscriber and a list, and it carries the `unsubscribed_at` timestamp that marks a list-level opt-out. Subscriptions on dynamic lists are not included. Records with a `delete_at` value have been removed from their list and are still returned; filter them out if you only want current subscriptions. This endpoint is not paginated and returns raw subscription records. # Bulk globally subscribe a list with the Marketing API Source: https://docs.paubox.com/marketing/subscriptions/bulk-global-subscribe openapi2 POST /subscriptions/bulk_global_subscribe Clears the global opt-out for a whole subscription list without having to enumerate every subscriber. This endpoint has two modes: - **Explicit** — supply `subscriber_ids` and the request behaves exactly like [`POST /subscriptions/subscribe`](/marketing/subscriptions/subscribe), returning the affected subscribers synchronously. - **Select-all** — omit `subscriber_ids` and supply `from_subscription_list_id`. Every subscriber matching `search` and `filters` in that list, minus `except_ids`, is queued for processing in the background and a Sidekiq job ID (`jid`) is returned immediately. In select-all mode `from_subscription_list_id` is required and must be a subscription list UUID. # Bulk globally unsubscribe a list with the Marketing API Source: https://docs.paubox.com/marketing/subscriptions/bulk-global-unsubscribe openapi2 POST /subscriptions/bulk_global_unsubscribe Globally opts out every subscriber in a subscription list without having to enumerate them. This endpoint has two modes: - **Explicit** — supply `subscriber_ids` and the request behaves exactly like [`POST /subscriptions/unsubscribe`](/marketing/subscriptions/unsubscribe), returning the affected subscribers synchronously. - **Select-all** — omit `subscriber_ids` and supply `from_subscription_list_id`. Every subscriber matching `search` and `filters` in that list, minus `except_ids`, is queued for processing in the background and a Sidekiq job ID (`jid`) is returned immediately. In select-all mode `from_subscription_list_id` is required and must be a subscription list UUID. Globally opting a subscriber out suppresses all future marketing email to them, across every list. # Create a subscription with the Marketing API Source: https://docs.paubox.com/marketing/subscriptions/create openapi2 POST /subscriptions Subscribes an existing subscriber to an existing subscription list. Creating a subscription fires any drip campaign configured with a `subscription_created` trigger on that list. A subscriber may only be subscribed to a given list once; a duplicate request fails validation. **Note on `subscriber_id`:** this field takes the subscriber's internal numeric ID, not the UUID returned by the subscriber endpoints. To add a subscriber to a list by UUID, use [`POST /subscribers`](/marketing/subscribers/create) with a `subscription_list_id`, or [`POST /subscriptions/subscribe`](/marketing/subscriptions/subscribe) to re-subscribe an existing subscription. **Example curl command:** ```bash curl -X POST \ https://api.paubox.com/v1/marketing/subscriptions \ -H 'authorization: Token token=YOUR_API_KEY' \ -H 'content-type: application/json' \ -d '{ "subscription": { "subscription_list_id": "123e4567-e89b-12d3-a456-426614174000", "subscriber_id": 4821 } }' ``` # Unsubscribe a subscription with the Marketing API Source: https://docs.paubox.com/marketing/subscriptions/delete openapi2 DELETE /subscriptions/{subscription_id} Unsubscribes the subscriber from the list this subscription belongs to by stamping `unsubscribed_at`. The subscription record itself is kept, and the subscriber stays subscribed to every other list and is not globally opted out. To re-subscribe, use [`POST /subscriptions/subscribe`](/marketing/subscriptions/subscribe). # Bulk subscribe a dynamic list with the Marketing API Source: https://docs.paubox.com/marketing/subscriptions/dynamic-bulk-subscribe openapi2 POST /subscriptions/dynamic_bulk_subscribe The dynamic list counterpart to [bulk global subscribe](/marketing/subscriptions/bulk-global-subscribe). - **Explicit** — supply `subscriber_ids` and the request behaves exactly like [`POST /subscriptions/subscribe`](/marketing/subscriptions/subscribe). - **Select-all** — omit `subscriber_ids` and supply `from_subscription_list_id`, which here is a **dynamic list** UUID. The job resolves the list's current membership, subtracts `except_ids`, and clears the global opt-out on the rest. A Sidekiq job ID (`jid`) is returned immediately. A dynamic list's membership is defined by the filters saved on the list itself, so any `filters` sent with the request is ignored in select-all mode. # Bulk unsubscribe a dynamic list with the Marketing API Source: https://docs.paubox.com/marketing/subscriptions/dynamic-bulk-unsubscribe openapi2 POST /subscriptions/dynamic_bulk_unsubscribe The dynamic list counterpart to [bulk global unsubscribe](/marketing/subscriptions/bulk-global-unsubscribe). - **Explicit** — supply `subscriber_ids` and the request behaves exactly like [`POST /subscriptions/unsubscribe`](/marketing/subscriptions/unsubscribe). - **Select-all** — omit `subscriber_ids` and supply `from_subscription_list_id`, which here is a **dynamic list** UUID. The job resolves the list's current membership, subtracts `except_ids`, and globally opts out the rest. A Sidekiq job ID (`jid`) is returned immediately. A dynamic list's membership is defined by the filters saved on the list itself, so any `filters` sent with the request is ignored in select-all mode. # Get a subscription with the Marketing API Source: https://docs.paubox.com/marketing/subscriptions/get openapi2 GET /subscriptions/{subscription_id} Returns a single subscription by its UUID. # Subscribe subscribers with the Marketing API Source: https://docs.paubox.com/marketing/subscriptions/subscribe openapi2 POST /subscriptions/subscribe Re-subscribes one or more subscribers, identified by their UUIDs. When `subscription_list_ids` is supplied, the matching subscriptions have their `unsubscribed_at` cleared. When it is omitted, only the global opt-out (`opted_out_on`) is cleared and list-level opt-outs are left untouched. In both cases the global opt-out is cleared, because a subscriber who is subscribed to any list is by definition not globally unsubscribed. **Example curl command:** ```bash curl -X POST \ https://api.paubox.com/v1/marketing/subscriptions/subscribe \ -H 'authorization: Token token=YOUR_API_KEY' \ -H 'content-type: application/json' \ -d '{ "subscriber_ids": ["8f14e45f-ceea-467a-9f2c-4b3d2a1e5c60"], "subscription_list_ids": ["123e4567-e89b-12d3-a456-426614174000"] }' ``` # Unsubscribe subscribers with the Marketing API Source: https://docs.paubox.com/marketing/subscriptions/unsubscribe openapi2 POST /subscriptions/unsubscribe Unsubscribes one or more subscribers, identified by their UUIDs. When `subscription_list_ids` is supplied, the matching subscriptions are stamped with `unsubscribed_at` and the subscribers remain subscribed to every other list. When it is omitted, the subscribers are globally opted out by stamping `opted_out_on`, which suppresses all future marketing email to them. **Example curl command:** ```bash curl -X POST \ https://api.paubox.com/v1/marketing/subscriptions/unsubscribe \ -H 'authorization: Token token=YOUR_API_KEY' \ -H 'content-type: application/json' \ -d '{ "subscriber_ids": ["8f14e45f-ceea-467a-9f2c-4b3d2a1e5c60"], "subscription_list_ids": ["123e4567-e89b-12d3-a456-426614174000"] }' ``` # List tracking links with the Marketing API Source: https://docs.paubox.com/marketing/tracking-links openapi2 GET /tracking_links Returns every link in every email sent in a campaign send, with its tracking info. Pass the send's ID nested under `tracking_link`: `?tracking_link[campaign_mailing_send_id]=SEND_ID`. A flat `?campaign_mailing_send_id=` query returns `400`. Results are paginated with `items` and `page`, and pagination metadata is returned in the response headers. **Note:** The campaign_mailing_send_id is available from the Paubox Marketing interface analytics page. Expand a sent campaign, click **Show More Analytics**, and copy the `campaignId=` value from the URL. **Example curl command:** ```bash curl -G \ https://api.paubox.com/v1/marketing/tracking_links \ -H 'authorization: Token token=YOUR_API_KEY' \ --data-urlencode 'tracking_link[campaign_mailing_send_id]=1308ab8d-a128-498c-8367-f71ac16934e8' ``` # MCP Server authentication Source: https://docs.paubox.com/mcp-server/authentication Get a Paubox API key and pass it to the Paubox MCP Server with the OAuth connector, request headers, environment variables, or per-call tool parameters on HTTP. The Paubox MCP Server authenticates against the Paubox Email API on your behalf. You provide your API key once when configuring the connection. A key set on the connection (the OAuth connector, a request header, or an environment variable) is not passed through the AI model. **1. Sign up for a Paubox account** If you don't have one, [sign up for Paubox Email API](https://www.paubox.com/pricing/paubox-email-api). Free tier includes up to 300 emails per month. **2. Add and verify your domain** Go to [Paubox Email API > Domains](https://next.paubox.com/settings/domains) and add the domain you will send from. Complete domain verification before generating an API key; unverified domains cannot send email. **3. Generate an API key** From [Paubox Email API > API Keys](https://next.paubox.com/settings/api_keys), press **Add API Key**. Give the key a name, select the **Paubox Email API** scope (add **Paubox Forms** if you'll use the Forms management tools), and choose your verified sender domain. Copy the key when it's created; it is displayed only once. **4. Pass your API key to the MCP server** How you pass the key depends on the transport. Over HTTP, every request must carry a credential, either an OAuth Bearer token or the `x-paubox-api-key` header; requests with neither are rejected. If both are sent, the header wins. Over stdio, the key comes only from the `PAUBOX_API_KEY` environment variable. **1. OAuth connector form (HTTP, recommended for Claude.ai and Claude Desktop)** Add `https://mcp.paubox.com` as a connector. The client presents a **Configure Paubox** form automatically. Enter your API key once; the client stores a short-lived encrypted Bearer token and sends it on every subsequent request. **2. Custom request headers (HTTP)** Some MCP clients let you set custom headers on the connector. Pass: ``` x-paubox-api-key: your_api_key ``` **3. Environment variables (stdio / Claude Code)** The stdio server exits at startup if `PAUBOX_API_KEY` is missing or shorter than 10 characters. ```bash theme={null} export PAUBOX_API_KEY=your_api_key ``` Claude Code / stdio config: ```json theme={null} { "mcpServers": { "paubox": { "command": "npx", "args": ["-y", "@paubox/mcp@latest"], "env": { "PAUBOX_API_KEY": "your_api_key" } } } } ``` **4. Per-call tool parameters (HTTP only)** Over HTTP, every tool except `submit_form` accepts an optional `apiKey` parameter. When passed, it overrides the key from the header or OAuth token for that call. The request still needs its own header or Bearer credential to reach the server. The stdio server does not accept an `apiKey` parameter. > [!NOTE] > > Never commit API keys to source control. Use environment variables or a secrets manager to inject credentials at runtime. ## Required permissions | Tools | Credential required | | :- | :- | | Email, scheduling, receiving, and webhook tools, plus `validate_credentials` | Paubox Email API key | | Email Marketing tools | The same Paubox Email API key, on an account with Email Marketing provisioned | | Forms management tools (`list_forms`, `create_form`, `update_form`, `archive_form`, `unarchive_form`, `copy_form`, `get_form_stats`, `list_form_submissions`, `export_submissions_csv`, `export_submission_pdf`) | API key with the `forms` scope | | `get_form` | None for active forms. An API key with the `forms` scope also returns inactive and archived forms | | `submit_form` | None (public endpoint) | See [MCP tools](/mcp-server/tools) for the tools in each area. `get_form` and `submit_form` call public Forms API endpoints, but the server connection itself still needs a credential: the HTTP transport rejects requests without a header or Bearer token, and the stdio server does not start without `PAUBOX_API_KEY`. # Paubox MCP Server Source: https://docs.paubox.com/mcp-server/index The Paubox MCP Server gives AI assistants HIPAA compliant email and secure form tools through the Model Context Protocol. The Paubox MCP Server lets AI assistants send HIPAA compliant email and work with Paubox Forms by calling Paubox tools through the Model Context Protocol (MCP). Once connected, a client like Claude, Claude Desktop, Cursor, or any other MCP-compatible host can send encrypted email, check delivery status, fetch Paubox Form definitions, and submit form responses. The server runs the Paubox API calls on your behalf. ## What you can build with it Healthcare teams use the Paubox MCP Server to: * Draft and send encrypted appointment reminders, follow-ups, and care instructions from inside a clinical AI assistant * Run an intake conversation that fetches a Paubox Form, collects answers, and submits the response without copying data between tools * Add email delivery and status checks to multi-step agent workflows that span scheduling, billing, or patient outreach ## Available tools The server exposes 50 tools across these areas: | Area | What it covers | | :- | :- | | Email | Send HIPAA compliant email, check delivery status, and validate your API key | | Scheduling | Schedule, look up, reschedule, and cancel email for future delivery | | Receiving | Manage receiving domains and mailboxes, and read inbound email and attachments | | Forms | Fetch and submit Paubox Forms, and with a `forms`-scoped key, manage forms and export submissions | | Email Marketing | Manage subscribers and lists, and report on campaign sends and deliveries | | Webhooks | Create and manage Email API webhook endpoints | See [MCP tools](/mcp-server/tools) for the full parameter reference for each tool ## Compatible clients Any client that follows the MCP specification can connect to the Paubox MCP Server, including: * Claude (via Settings > Connectors on [claude.ai](http://claude.ai)) * Claude Desktop * Cursor, Windsurf, and other MCP-aware IDEs * Custom agents and scripts built on the MCP specification The server supports two transports, so clients can pick whichever they natively use: * HTTP at `https://mcp.paubox.com`: authenticate via the OAuth connector form (Claude.ai, and clients that receive the OAuth callback on `localhost`), or set the `x-paubox-api-key` header * stdio via `npx @paubox/mcp@latest` with `PAUBOX_API_KEY` in the environment (requires Node.js ≥ 22) ## How it handles HIPAA and credentials Email sent through the Paubox MCP Server is encrypted by the Paubox Email API, the same HIPAA compliant transactional email service that Paubox provides to healthcare developers. Messages count against your Email API plan and appear in your Paubox dashboard alongside the rest of your API traffic. When you supply your API key through the OAuth connector, the `x-paubox-api-key` header, or the `PAUBOX_API_KEY` environment variable, it travels with the client's connection to the server, not through the AI model. Over HTTP, tools also accept an optional `apiKey` parameter; a key passed that way is part of the tool call, so prefer the connection-level options. See [Authentication](/mcp-server/authentication). ## Get started > [card] [Quickstart](/mcp-server/quickstart) > > Connect Claude, Claude Desktop, or any MCP client. > [card] [MCP tools](/mcp-server/tools) > > See parameters and responses for every tool. > [card] [Authentication](/mcp-server/authentication) > > Generate a Paubox Email API key and configure credentials. > [card] [Email API](/email-api) > > Learn more about the underlying Paubox Email API ## FAQs > [accordion] What is the Paubox MCP Server? > > It is a Model Context Protocol server hosted at `https://mcp.paubox.com` that gives AI assistants access to the Paubox Email API, Email Marketing, and Paubox Forms. Agents can send HIPAA compliant email and submit secure intake forms as native tool calls. > [accordion] Does it work with Claude? > > Yes. Connect through Settings > Connectors on claude.ai, or add the server to `claude_desktop_config.json` for Claude Desktop. The [Quickstart](/mcp-server/quickstart) covers both setups. > [accordion] Does the Paubox MCP Server require a separate plan? > > No. It uses your existing [Paubox Email API](https://www.paubox.com/products/paubox-email-api) account. The Email API free tier covers 300 emails per month. > [accordion] Is the API key ever shared with the AI model > > Not when it comes from the OAuth connector, a request header, or an environment variable: those credentials travel with the connection, and the assistant calls tools by name. A key passed in the optional `apiKey` tool parameter is part of the tool call itself. > [accordion] Which transports does the server support? > > HTTP at `https://mcp.paubox.com`, and stdio via the `@paubox/mcp` npm package. ## Community & support > [card] [Q\&A](https://github.com/Paubox/community/discussions/categories/paubox-mcp-cli) > > Ask usage questions in the Paubox Community. > [card] [Ideas](https://github.com/Paubox/community/discussions/categories/ideas) > > Propose features and improvements. > [!WARNING] > > Never post PHI, recipient addresses, or message content in public threads. Account, billing, or anything sensitive goes to [support@paubox.com](mailto:support@paubox.com). # MCP Server quickstart Source: https://docs.paubox.com/mcp-server/quickstart Connect the Paubox MCP Server to Claude, Claude Desktop, Claude Code, or any MCP-compatible client. > [!WARNING] > > **HIPAA Notice:** If you plan to send or reference PHI when using the Paubox MCP connector through Claude, you must have a Business Associate Agreement (BAA) in place with Anthropic. BAAs are available on Claude Team and Enterprise plans. Your Paubox subscription covers email delivery, it does not cover protected health information (PHI) processed within Claude's context window. > [!NOTE] > > **Picking a transport:** the hosted HTTP connector (`https://mcp.paubox.com`) needs nothing installed. The stdio option runs the [`@paubox/mcp`](https://www.npmjs.com/package/@paubox/mcp) npm package on your own machine and requires **Node.js ≥ 22** — a higher floor than the [Paubox CLI](/cli/installation), which supports Node.js ≥ 20.12.0, so a machine that runs the CLI will not necessarily run the stdio server. `npm` only warns on a version mismatch rather than refusing, so check `node --version` before assuming a failed stdio launch is a credential problem. **1. Get your API key** Before connecting, you need a Paubox Email API key. See [Authentication](/mcp-server/authentication) for how to generate one from the Paubox dashboard. **2. Connect via Claude.ai** 1. In [Claude.ai](https://claude.ai), open **Settings > Connectors**. 2. Click **Add connector** and enter the server URL: ``` https://mcp.paubox.com ``` 3. A **Configure Paubox** form opens automatically. Enter your API key. 4. Click **Save**. Claude stores your API key as a secure token and sends it on every request. Claude will discover the available Paubox tools automatically. **3. Connect via Claude Desktop** Open (or create) `claude_desktop_config.json` and add the `paubox` entry to `mcpServers`: ```json claude_desktop_config.json (HTTP, recommended) theme={null} { "mcpServers": { "paubox": { "url": "https://mcp.paubox.com" } } } ``` ```json claude_desktop_config.json (stdio) theme={null} { "mcpServers": { "paubox": { "command": "npx", "args": ["-y", "@paubox/mcp@latest"], "env": { "PAUBOX_API_KEY": "YOUR_API_KEY" } } } } ``` The config file is located at: * **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json` * **Windows**: `%APPDATA%\Claude\claude_desktop_config.json` When using the HTTP config, Claude Desktop will open a browser window to the Configure Paubox form to collect your credentials. Restart Claude Desktop after saving. **4. Connect via Claude Code** Run this command once with your API key (no credential prompts afterward): ```bash theme={null} claude mcp add paubox \ -e PAUBOX_API_KEY=your_api_key \ -- npx @paubox/mcp@latest ``` Claude Code spawns the package locally and injects the API key as an environment variable. **5. Test the connection** Ask Claude to verify your credentials: > "Use the Paubox MCP server to validate my credentials." Claude will call `validate_credentials` and confirm your API key is working. Then try sending a test email: > "Send a test email to [me@example.com](mailto:me@example.com) from [sender@yourdomain.com](mailto:sender@yourdomain.com) with the subject 'Hello from MCP'." Claude will call `send_secure_email` and return a `sourceTrackingId` you can use to check delivery status. ## Other MCP-compatible clients Any client that supports the MCP specification can connect using either transport: * **HTTP**: `https://mcp.paubox.com`; set `x-paubox-api-key` as a custom request header. The OAuth credential form works for clients that receive the OAuth callback on `localhost`. * **stdio**: run `npx @paubox/mcp@latest` with `PAUBOX_API_KEY` set in the environment # MCP tools Source: https://docs.paubox.com/mcp-server/tools Reference for every tool the Paubox MCP Server exposes for sending and scheduling email, receiving inbound mail, Forms, Email Marketing, and webhooks. The Paubox MCP Server exposes 50 tools across five areas: [Email](#email), [Receiving](#receiving), [Forms](#forms), [Email Marketing](#email-marketing), and [Webhooks](#webhooks). Each tool maps to an underlying Paubox API operation. All 50 tools are available over both transports: the hosted HTTP server at `https://mcp.paubox.com/mcp` and the `@paubox/mcp` stdio package. How each one receives your API key is the only difference. > [!NOTE] > > **The optional `apiKey` parameter listed on the tools below exists only on the HTTP transport, on every tool except `submit_form`.** Over stdio the key comes from the `PAUBOX_API_KEY` environment variable and the parameter is not accepted; omit it. Over HTTP a per-call `apiKey` overrides the key from the `x-paubox-api-key` header or OAuth token. > > Most parameters use camelCase (`formId`, `subscriptionListId`). The exceptions are `quota_bytes` on `create_receiving_mailbox` and every parameter of the [Webhooks](#webhooks) tools, which use snake\_case. ## Email ### send\_secure\_email Sends a single HIPAA compliant email through the Paubox Email API. The sender address must belong to a domain you have verified in the Paubox dashboard. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `from` | string | Yes | Sender address. Must be on a verified Paubox domain. | | `to` | array of strings | Yes | Recipient email addresses. | | `subject` | string | Yes | Email subject line. | | `message` | string | Yes | Message body, as plain text. When `html` is omitted, the server also generates an HTML version from it: blank lines become paragraphs, single newlines become line breaks, markup characters are escaped, and bare URLs are made clickable. | | `html` | string | No | HTML body, used verbatim as the `text/html` part. `message` is still sent as the `text/plain` fallback. Omit it to have `message` rendered to HTML automatically. | | `cc` | array of strings | No | CC recipients. | | `bcc` | array of strings | No | BCC recipients. | | `forceSecureNotification` | boolean | No | Force a secure notification regardless of recipient settings. Defaults to `false`. | | `attachments` | array of objects | No | File attachments. Each item takes `fileName` (a bare filename such as `report.pdf`), `contentType` (MIME type, e.g. `application/pdf`) and `content` (the file, base64-encoded). 25 MB total across all attachments. | | `apiKey` | string | No | Paubox API key. Overrides the credential resolved from the connector or headers. | **Example payload** ```json theme={null} { "from": "provider@clinic.com", "to": ["patient@example.com"], "subject": "Your appointment summary", "message": "Thank you for visiting us today." } ``` **Example payload with an HTML body** ```json theme={null} { "from": "provider@clinic.com", "to": ["patient@example.com"], "subject": "Your appointment summary", "message": "Thank you for visiting us today. Read your summary at https://clinic.example/summary", "html": "<p>Thank you for visiting us today.</p><p><a href=\"https://clinic.example/summary\">Read your summary</a></p>" } ``` > [!NOTE] > > Send `html` when the message is designed as an email — styled headings, linked phrases, an inline logo. Because the automatic HTML version escapes markup characters, markup placed in `message` arrives as literal text; `html` is the way to send real markup. It is used exactly as given and is not sanitized, so send only markup you control, and keep `message` a readable plain-text equivalent for clients that do not render HTML. `schedule_email` accepts `html` in exactly the same form. **Example payload with an attachment** ```json theme={null} { "from": "provider@clinic.com", "to": ["patient@example.com"], "subject": "Your appointment summary", "message": "Your visit summary is attached.", "attachments": [ { "fileName": "visit-summary.pdf", "contentType": "application/pdf", "content": "JVBERi0xLjQKJcfsj6IKNSAwIG9iago8PC9MZW5..." } ] } ``` > [!NOTE] > > `content` must be the base64 encoding of the file's bytes, with no `data:` URI prefix. `fileName` must be a bare filename — a path such as `reports/visit.pdf` is rejected. `schedule_email` accepts `attachments` in exactly the same form. **Response:** returns a `sourceTrackingId` string you can pass to `check_email_status`. ### check\_email\_status Retrieves the current delivery status of a message sent via `send_secure_email`. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `sourceTrackingId` | string | Yes | The tracking ID returned by `send_secure_email`. | | `apiKey` | string | No | Paubox API key. | **Example payload** ```json theme={null} { "sourceTrackingId": "abc123def456" } ``` **Response:** returns an object with delivery disposition details and a timestamp. ### schedule\_email Schedules a HIPAA compliant email for future delivery. The message is queued and sent at the specified time. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `from` | string | Yes | Sender address. Must be on a verified Paubox domain. | | `to` | array of strings | Yes | Recipient email addresses. | | `subject` | string | Yes | Email subject line. | | `message` | string | Yes | Message body, as plain text. When `html` is omitted, the server also generates an HTML version from it: blank lines become paragraphs, single newlines become line breaks, markup characters are escaped, and bare URLs are made clickable. | | `html` | string | No | HTML body, used verbatim as the `text/html` part. `message` is still sent as the `text/plain` fallback. Omit it to have `message` rendered to HTML automatically. | | `scheduledAt` | string | Yes | ISO 8601 datetime for when the email should be sent (e.g. `2025-12-25T15:00:00Z`). | | `cc` | array of strings | No | CC recipients. | | `bcc` | array of strings | No | BCC recipients. | | `forceSecureNotification` | boolean | No | Force a secure notification regardless of recipient settings. Defaults to `false`. | | `attachments` | array of objects | No | File attachments. Each item takes `fileName` (a bare filename such as `report.pdf`), `contentType` (MIME type, e.g. `application/pdf`) and `content` (the file, base64-encoded). 25 MB total across all attachments. | | `apiKey` | string | No | Paubox API key. | **Example payload** ```json theme={null} { "from": "provider@clinic.com", "to": ["patient@example.com"], "subject": "Your appointment reminder", "message": "Your appointment is tomorrow at 10am.", "scheduledAt": "2025-12-25T15:00:00Z" } ``` **Response:** returns a `sourceTrackingId`, `scheduledAt`, and `state`. Save the tracking ID to check status, reschedule, or cancel. ### get\_scheduled\_email Checks the status of a scheduled email. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `sourceTrackingId` | string | Yes | The tracking ID returned by `schedule_email`. | | `apiKey` | string | No | Paubox API key. | **Example payload** ```json theme={null} { "sourceTrackingId": "abc123def456" } ``` **Response:** returns the scheduled email's `state` (e.g. `pending`, `sent`, `cancelled`) and `scheduledAt` time. ### reschedule\_email Changes the scheduled delivery time of a pending email. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `sourceTrackingId` | string | Yes | The tracking ID returned by `schedule_email`. | | `scheduledAt` | string | Yes | New ISO 8601 datetime for when the email should be sent. | | `apiKey` | string | No | Paubox API key. | **Example payload** ```json theme={null} { "sourceTrackingId": "abc123def456", "scheduledAt": "2025-12-26T10:00:00Z" } ``` **Response:** returns the updated `scheduledAt` and current `state`. ### cancel\_scheduled\_email Cancels a scheduled email that has not yet been sent. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `sourceTrackingId` | string | Yes | The tracking ID returned by `schedule_email`. | | `apiKey` | string | No | Paubox API key. | **Example payload** ```json theme={null} { "sourceTrackingId": "abc123def456" } ``` **Response:** returns the tracking ID and updated `state` (`cancelled`). ### validate\_credentials Verifies that the Paubox API credentials are present and valid by making a live check against the Paubox API. Useful as a first step before sending email. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `apiKey` | string | No | Paubox API key. Pass if you want to validate a specific API key rather than the one already configured. | When connecting via stdio (Claude Code), the API key comes from an environment variable and no parameters are needed. **Example payload** ```json theme={null} {} ``` **Response:** returns a confirmation with a masked API key on success, or an error description if the API key is missing or invalid. ## Receiving Manage inbound email domains, mailboxes, and messages. These tools use the same API key as the email tools. ### list\_receiving\_domains Lists all receiving domains for the authenticated account. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `apiKey` | string | No | Paubox API key. | **Response:** returns an array of receiving domains with `id`, `domain`, and `state`. ### create\_receiving\_domain Provisions a new receiving domain under `inbound.paubox.email`. DNS is configured automatically. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `slug` | string | No | Custom subdomain slug. Auto-generated if omitted. | | `apiKey` | string | No | Paubox API key. | **Example payload** ```json theme={null} { "slug": "support" } ``` **Response:** returns the created domain, including its full `domain` name and `state`. ### get\_receiving\_domain Retrieves a receiving domain by ID. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `id` | string | Yes | Domain ID. | | `apiKey` | string | No | Paubox API key. | **Response:** returns the domain with `id`, `domain`, `state`, and `dns_records`. ### delete\_receiving\_domain Deletes a receiving domain and all its mailboxes. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `id` | string | Yes | Domain ID. | | `apiKey` | string | No | Paubox API key. | **Response:** returns an empty object on success. ### list\_receiving\_mailboxes Lists all mailboxes on a receiving domain. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `domainId` | string | Yes | Receiving domain ID. | | `apiKey` | string | No | Paubox API key. | **Response:** returns an array of mailboxes with `id`, `email`, and `quota_bytes`. ### create\_receiving\_mailbox Creates a new mailbox on a receiving domain. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `domainId` | string | Yes | Receiving domain ID. | | `name` | string | Yes | Local part of the mailbox address. | | `password` | string | Yes | Mailbox password. | | `quota_bytes` | integer | No | Storage quota in bytes. | | `apiKey` | string | No | Paubox API key. | **Example payload** ```json theme={null} { "domainId": "1", "name": "intake", "password": "SecurePass123!" } ``` **Response:** returns the created mailbox, including its full `email` address. ### get\_receiving\_mailbox Retrieves a mailbox by domain and mailbox ID. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `domainId` | string | Yes | Receiving domain ID. | | `mailboxId` | string | Yes | Mailbox ID. | | `apiKey` | string | No | Paubox API key. | **Response:** returns the mailbox details. ### delete\_receiving\_mailbox Deletes a mailbox. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `domainId` | string | Yes | Receiving domain ID. | | `mailboxId` | string | Yes | Mailbox ID. | | `apiKey` | string | No | Paubox API key. | **Response:** returns an empty object on success. ### list\_received\_emails Lists received emails across all active receiving domains, sorted by most recent. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `limit` | integer | No | Max emails to return (1–100, default 25). | | `after` | string | No | Cursor for forward pagination. | | `before` | string | No | Cursor for backward pagination. | | `apiKey` | string | No | Paubox API key. | **Response:** returns `data` (array of emails), `has_more`, and `object: "list"`. ### get\_received\_email Retrieves a single received email with full content, headers, and attachment metadata. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `emailId` | string | Yes | Email ID. | | `apiKey` | string | No | Paubox API key. | **Response:** returns the email with `from`, `to`, `subject`, `body` (text and html), and `attachments`. ### get\_received\_email\_attachment Downloads a received email attachment. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `emailId` | string | Yes | Email ID (UUID). | | `attachmentId` | string | Yes, unless `blobId` is passed | Attachment UUID: the `id` of an entry in the `attachments` returned by `get_received_email`. | | `blobId` | string | No | Deprecated alias for `attachmentId`. | | `apiKey` | string | No | Paubox API key. | **Response:** returns JSON with `filename`, `content_type`, `size`, and the file base64-encoded in `content_base64`. Attachments over 1 MB are refused; fetch those from the attachment's `download_url` instead. ## Forms The two tools below need no credentials. Everything after them manages forms and submissions and requires an API key carrying the `forms` scope, sent as a Bearer token; scoped keys are managed in the Paubox admin dashboard. See [Forms authentication](/forms/authentication). ### get\_form Retrieves the full definition of a Paubox Form, including its title, description, and field schema, so an agent can present the form questions in a conversation. No authentication is required for active forms. When an API key carrying the `forms` scope is available, inactive and archived forms become retrievable too. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `formId` | string (UUID) | Yes | UUID of the Paubox Form to retrieve. | | `apiKey` | string | No | Paubox API key with the `forms` scope. Enables retrieving inactive and archived forms. | **Example payload** ```json theme={null} { "formId": "550e8400-e29b-41d4-a716-446655440000" } ``` **Response:** returns a form object including `title`, `description`, `form_json` (field definitions), and metadata fields (`active`, `signable`, `submission_count`, `created_at`, `updated_at`). ### submit\_form Submits a completed response to a Paubox Form. No authentication is required for this tool. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `formId` | string (UUID) | Yes | UUID of the form being submitted. | | `formData` | object | Yes | Key-value pairs matching the form's field schema (`form_json`). Structure varies per form. | | `attachments` | array of objects | No | File attachments. Each object must include `name` (filename) and `content` (base64-encoded file). Max total size: 250 MB. | **Example payload: text fields only** ```json theme={null} { "formId": "550e8400-e29b-41d4-a716-446655440000", "formData": { "first_name": "Jane", "last_name": "Smith", "email": "jane@example.com" } } ``` **Example payload: with attachment** ```json theme={null} { "formId": "550e8400-e29b-41d4-a716-446655440000", "formData": { "first_name": "Jane", "consent_form": "consent.pdf" }, "attachments": [ { "name": "consent.pdf", "content": "JVBERi0xLjQK" } ] } ``` **Response:** returns a success confirmation message on success. ### list\_forms Lists a customer's Paubox Forms with search, filtering, ordering, and pagination. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `customerId` | integer | Yes | Paubox customer ID the forms belong to. | | `search` | string | No | Search text matched against form title and description. | | `formId` | string (UUID) | No | Filter to a specific form. | | `archived` | boolean | No | Filter by archived status. | | `active` | boolean | No | Filter by active status. | | `orderBy` | string | No | Sort field: `title`, `updated_at`, or `submission_count`. Defaults to `created_at`. | | `order` | string | No | `asc` or `desc`. Defaults to `desc`. | | `page` | integer | No | Page number. Defaults to `1`. | | `items` | integer | No | Items per page. Defaults to `50`, maximum `100`. | | `apiKey` | string | No | Paubox API key with the `forms` scope. | **Example payload** ```json theme={null} { "customerId": 1234, "active": true, "orderBy": "submission_count", "order": "desc" } ``` **Response:** returns a paginated list of form objects with title, status, and submission counts. ### create\_form Creates a new Paubox Form. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `title` | string | Yes | Form title. | | `formJson` | object | Yes | Form schema (`form_json`) — an object with a `body` array of components. See [Form schema](#form-schema-formjson) below. Pass the object itself; a JSON-encoded string is also parsed. | | `customerId` | integer | Yes | Paubox customer ID that owns the form. | | `description` | string | No | Form description. | | `formHtml` | string | No | Rendered form HTML. | | `formCss` | string | No | Form CSS. | | `recipient` | string | No | Comma-separated email addresses that receive submission notifications. | | `signable` | boolean | No | Whether the form collects a signature. | | `signatureConfirmationLabel` | string | No | Label shown next to the signature confirmation checkbox. | | `subscriptionListId` | string | No | Subscription list to add submitters to. | | `type` | string | No | Form type, for example `marketing_form`. | | `active` | boolean | No | Whether the form is active. Defaults to `false`. | | `version` | integer | No | Form version. Defaults to `1`. | | `apiKey` | string | No | Paubox API key with the `forms` scope. | **Example payload** ```json theme={null} { "customerId": 1234, "title": "Patient intake", "recipient": "intake@clinic.com", "active": true, "formJson": { "body": [ { "type": "Text", "id": "pi-01", "properties": { "font": "%{defaultFont}", "font_size": "22px", "color": "%{defaultLabelColor}", "text_align": "left", "margin": "4px", "text": "<p><strong>Patient intake</strong></p>" } }, { "type": "TextInput", "id": "pi-02", "properties": { "label_enabled": true, "label_position": "Top", "label_font": "%{defaultFont}", "label_font_size": "16px", "label_color": "%{defaultLabelColor}", "text_align": "left", "margin": "4px", "subtext_enabled": false, "subtext": "", "field_name": "first_name", "required": true, "text": "<p>First name</p>", "placeholder_text": "Enter text here", "input_mask": "Any", "input_color": "%{defaultInputColor}" } }, { "type": "Button", "id": "pi-03", "properties": { "margin": "4px", "full_width": true, "button_position": "Center", "button_roundness": "4px", "button_color": "%{defaultSelectedColor}", "label_enabled": true, "text": "<p><strong>Submit</strong></p>", "label_position": "Top", "label_font": "%{defaultFont}", "label_font_size": "16px", "label_color": "#fff", "text_align": "center", "subtext_enabled": false, "subtext": "" } } ] } } ``` **Response:** returns the created form, including its UUID. ### Form schema (`formJson`) `formJson` is **not** a free-form field list. The Paubox form renderer reads exactly one top-level key, `body`, holding an ordered array of components. Anything else is stored verbatim and renders as an empty form, with no error (PPD-9105). Each entry in `body` needs three keys: | Key | Type | Description | | :- | :- | :- | | `type` | string | One of the component types below. Case-sensitive. | | `id` | string | Unique within the form. Any stable string; the builder uses short random ids. | | `properties` | object | Per-type settings. Keys are **`snake_case`** on the wire. | **Component types:** `Text`, `Divider`, `TextInput`, `TextArea`, `Dropdown`, `Checkboxes`, `Radiobutton`, `FileUpload`, `Signature`, `Button`, `Conditional`, `Logo`. Note `Radiobutton` — lowercase `b`, unlike the others. **Input components** (`TextInput`, `TextArea`, `Dropdown`, `Checkboxes`, `Radiobutton`, `FileUpload`, `Signature`) carry the label block — `label_enabled`, `label_position`, `label_font`, `label_font_size`, `label_color`, `text_align`, `margin`, `subtext_enabled`, `subtext` — plus: | Property | Applies to | Description | | :- | :- | :- | | `field_name` | all inputs | The key this field's answer appears under in a submission. Slugified label, e.g. `first_name`. Must be unique within the form. | | `required` | all inputs | Boolean. | | `text` | all inputs | The visible label, as HTML: `"<p>First name</p>"`. | | `placeholder_text` | `TextInput`, `TextArea`, `Signature` | Placeholder copy. | | `input_mask` | `TextInput` | One of `"Any"` (default, no mask), `"Email"`, `"Phone Number"`, `"Number"`, `"Date"`, `"SSN"`, `"ZIP Code"`. An unrecognized value is silently treated as `"Any"`. | | `input_color` | `TextInput`, `TextArea` | Usually the `%{defaultInputColor}` token. | | `choices` | `Dropdown`, `Checkboxes`, `Radiobutton` | Array of `{ "value": "Displayed text", "id": "0" }`. | | `signature_type` | `Signature` | `"Drawn Signature"`. | **Static components** (`Text`, `Divider`, `Button`, `Logo`) take no `field_name` and never appear in submissions. `Text` uses `font`, `font_size`, `color`, `text_align`, `margin`, and `text` (HTML). > [!NOTE] > > Values like `%{defaultFont}` and `%{defaultLabelColor}` are theming tokens resolved against the > form's design settings at render time. Copy them as written rather than substituting literal > fonts and colors, so the form follows the customer's branding. > [!TIP] > > An agent can build a `body` array from a fillable PDF's extracted fields and create a matching Paubox Form in a single conversation. Map each PDF field to the component type above that matches it, slugify its label into `field_name`, and append a `Button` to submit. ### update\_form Updates an existing Paubox Form. Only the fields you provide change; omitted fields stay as they are. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `formId` | string (UUID) | Yes | UUID of the form to update. | | `title` | string | No | New form title. | | `description` | string | No | New form description. | | `formJson` | object | No | New form schema (`form_json`), same shape as [create\_form](#form-schema-formjson). Replaces the stored schema wholesale — send the complete `body`, not a partial one. | | `vanityUrl` | string | No | New vanity URL slug. | | `recipient` | string | No | Comma-separated email addresses that receive submission notifications. | | `active` | boolean | No | Set the form's active status. | | `subscriptionListId` | string | No | Subscription list to add submitters to. | | `apiKey` | string | No | Paubox API key with the `forms` scope. | **Example payload** ```json theme={null} { "formId": "550e8400-e29b-41d4-a716-446655440000", "active": false } ``` **Response:** returns the updated form. ### archive\_form Archives a Paubox Form. This sets `archived` to `true` and `active` to `false`. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `formId` | string (UUID) | Yes | UUID of the form to archive. | | `apiKey` | string | No | Paubox API key with the `forms` scope. | **Response:** returns the archived form. ### unarchive\_form Restores a previously archived Paubox Form. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `formId` | string (UUID) | Yes | UUID of the form to unarchive. | | `apiKey` | string | No | Paubox API key with the `forms` scope. | **Response:** returns the restored form. ### copy\_form Duplicates an existing Paubox Form under a new title. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `formId` | string (UUID) | Yes | UUID of the form to copy. | | `title` | string | Yes | Title for the new copy. | | `apiKey` | string | No | Paubox API key with the `forms` scope. | **Response:** returns the new form, including its UUID. ### get\_form\_stats Returns aggregate Paubox Forms statistics: active form count, total submission count, and submissions in the last 7 days. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `customerId` | integer | No | Paubox customer ID. Defaults to the API key's customer. | | `apiKey` | string | No | Paubox API key with the `forms` scope. | **Response:** returns `active_form_count`, `submission_count`, and `submissions_last_7_days`. ### list\_form\_submissions Lists a form's submissions, with each submission's `form_data` parsed into structured key/value pairs. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `formId` | string (UUID) | Yes | UUID of the form. | | `submissionId` | string (UUID) | No | Filter to a single submission. | | `orderBy` | string | No | Sort field: `submitter_email`. Defaults to `created_at`. | | `order` | string | No | `asc` or `desc`. | | `page` | integer | No | Page number. Defaults to `1`. | | `items` | integer | No | Items per page. Maximum `100`. | | `apiKey` | string | No | Paubox API key with the `forms` scope. | **Response:** returns submissions with parsed field data, submitter email, and attachment info. ### export\_submissions\_csv Exports a form's submissions as CSV text. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `formId` | string (UUID) | Yes | UUID of the form. | | `submissionId` | string (UUID) | No | Export only this submission. | | `apiKey` | string | No | Paubox API key with the `forms` scope. | **Response:** returns CSV text. ### export\_submission\_pdf Exports a single form submission as a PDF. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `formId` | string (UUID) | Yes | UUID of the form. | | `submissionId` | string (UUID) | Yes | UUID of the submission. | | `apiKey` | string | No | Paubox API key with the `forms` scope. | **Response:** returns the PDF, base64-encoded. ## Email Marketing These tools read and write Paubox Email Marketing data. They use the same API key as the email tools — no additional scope is required — but the account must have Email Marketing provisioned. Call `validate_marketing_access` first if another marketing tool reports that no marketing customer was found. > [!NOTE] > > This set is read-only plus safe subscriber and list writes. Campaign sending and bulk deletion are deliberately not exposed over MCP. Every tool below accepts an optional `apiKey` string parameter, which behaves as described above; it is omitted from the tables that have no other parameters. ### validate\_marketing\_access Checks whether the account has Email Marketing provisioned and returns the marketing customer profile. **Example payload** ```json theme={null} {} ``` **Response:** returns the marketing customer name, `from_name`, `from_email`, physical address, and global unsubscribe setting. ### list\_subscribers Lists Email Marketing subscribers. Omit `subscriptionListId` to search the account's default "All contacts" list. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `search` | string | No | Search text. Defaults to all subscribers. | | `subscriptionListId` | integer | No | Restrict to a subscription list. IDs come from `list_subscription_lists`. | | `dynamicListId` | string (UUID) | No | Restrict to a dynamic list. UUIDs come from `list_dynamic_lists`. | | `orderBy` | string | No | Sort field. Defaults to `created_at`. | | `order` | string | No | `asc` or `desc`. Defaults to `desc`. | | `page` | integer | No | Page number. Defaults to `1`. | | `items` | integer | No | Items per page. Defaults to `50`, capped at `200`. | | `withStats` | boolean | No | Include per-subscriber delivery statistics. | | `apiKey` | string | No | Paubox API key. | **Response:** returns a paginated list of subscribers. ### get\_subscriber Retrieves one subscriber by UUID, including custom field values and subscription list memberships. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `subscriberId` | string (UUID) | Yes | Subscriber UUID. | | `subscriptionListId` | integer | No | Report subscribed/unsubscribed relative to this subscription list. | | `dynamicListId` | string (UUID) | No | Report subscribed/unsubscribed relative to this dynamic list. | | `withStats` | boolean | No | Include this subscriber's delivery statistics. | | `apiKey` | string | No | Paubox API key. | **Response:** returns the subscriber object. ### create\_subscriber Adds a subscriber. Requires an email address or a phone number. The subscriber always joins the default "All contacts" list, plus `subscriptionListId` when given. An existing subscriber matching the same email or phone is updated rather than duplicated. Custom field names that do not exist yet are created automatically. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `email` | string | No\* | Subscriber email address. | | `phoneNumber` | string | No\* | Subscriber phone number, normalized to E.164. | | `firstName` | string | No | First name. | | `lastName` | string | No | Last name. | | `customFields` | array of objects | No | Custom field values. Each object has `name` and `value`. | | `subscriptionListId` | integer | No | Additional subscription list to subscribe them to. | | `apiKey` | string | No | Paubox API key. | \* One of `email` or `phoneNumber` is required. **Example payload** ```json theme={null} { "email": "jane@example.com", "firstName": "Jane", "subscriptionListId": 42, "customFields": [{ "name": "clinic", "value": "Downtown" }] } ``` **Response:** returns the created or updated subscriber. ### update\_subscriber Updates an existing subscriber by UUID. Only the fields you provide change. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `subscriberId` | string (UUID) | Yes | Subscriber UUID. | | `email` | string | No | New email address. | | `phoneNumber` | string | No | New phone number, normalized to E.164. | | `firstName` | string | No | New first name. | | `lastName` | string | No | New last name. | | `customFields` | array of objects | No | Custom field values to set. Each object has `name` and `value`. | | `subscriptionListId` | integer | No | Subscription list to also subscribe them to. | | `apiKey` | string | No | Paubox API key. | **Response:** returns the updated subscriber. ### get\_subscribed\_count Counts currently subscribed contacts on a list, excluding unsubscribed and deleted contacts. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `subscriptionListId` | integer | No | Subscription list ID. Defaults to the account's default list. | | `apiKey` | string | No | Paubox API key. | **Response:** returns the subscribed contact count. ### list\_subscriber\_custom\_fields Lists the custom subscriber field types defined for the account. Use this to discover which custom field names `create_subscriber` and `update_subscriber` can set. **Example payload** ```json theme={null} {} ``` **Response:** returns the account's custom field definitions. ### list\_marketing\_lists Lists all audiences — both static subscription lists and filter-based dynamic lists — in one view with subscriber counts. Use `list_subscription_lists` or `list_dynamic_lists` when you need one kind specifically. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `search` | string | No | Search text matched against list names. | | `orderBy` | string | No | `name`, `created_at`, `updated_at`, or `subscriber_count`. Defaults to `name`. | | `order` | string | No | `asc` or `desc`. Defaults to `asc`. | | `page` | integer | No | Page number. Enables pagination. | | `items` | integer | No | Items per page. Maximum `200`. | | `apiKey` | string | No | Paubox API key. | **Response:** returns all audiences with their kind, ID, and subscriber count. ### list\_subscription\_lists Lists static subscription lists with their integer IDs, subscriber counts, and which one is the default "All contacts" list. The IDs returned here are what `subscriptionListId` expects elsewhere. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `orderBy` | string | No | Sort field. Defaults to `name`. | | `order` | string | No | `asc` or `desc`. Defaults to `asc`. | | `page` | integer | No | Page number. Enables pagination. | | `items` | integer | No | Items per page. Maximum `200`. | | `apiKey` | string | No | Paubox API key. | **Response:** returns subscription lists with integer IDs and subscriber counts. ### create\_subscription\_list Creates a new, empty subscription list. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `name` | string | Yes | Name for the new subscription list. | | `apiKey` | string | No | Paubox API key. | **Response:** returns the new list's integer ID, for use with `create_subscriber` and `list_subscribers`. ### list\_dynamic\_lists Lists dynamic lists — filter-based segments that recompute their membership — with their UUIDs, filter definitions, and subscriber counts. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `orderBy` | string | No | Sort field. Defaults to `name`. | | `order` | string | No | `asc` or `desc`. Defaults to `asc`. | | `page` | integer | No | Page number. Enables pagination. | | `items` | integer | No | Items per page. Maximum `200`. | | `apiKey` | string | No | Paubox API key. | **Response:** returns dynamic lists with UUIDs, filter definitions, and subscriber counts. ### list\_campaign\_sends Lists campaign sends — each time a marketing email went out to a list — with per-send counts for delivered, viewed, clicked, bounced, and unsubscribed. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `search` | string | No | Search text matched against the send. | | `orderBy` | string | No | Sort field. Defaults to `created_at`. | | `order` | string | No | `asc` or `desc`. Defaults to `desc`. | | `page` | integer | No | Page number. Defaults to `1`. | | `items` | integer | No | Items per page. Maximum `200`. | | `apiKey` | string | No | Paubox API key. | **Response:** returns campaign sends with their integer IDs and per-send engagement counts. ### list\_campaign\_deliveries Lists individual deliveries — one row per recipient per campaign — showing what happened to each message. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `campaignMailingId` | integer | No | Restrict to one campaign mailing. | | `campaignMailingSendId` | integer | No | Restrict to one send of a campaign mailing. IDs come from `list_campaign_sends`. | | `search` | string | No | Search text. | | `orderBy` | string | No | Sort field. Defaults to `created_at`. | | `order` | string | No | `asc` or `desc`. Defaults to `desc`. | | `page` | integer | No | Page number. Defaults to `1`. | | `items` | integer | No | Items per page. Maximum `200`. | | `apiKey` | string | No | Paubox API key. | **Response:** returns per-recipient delivery rows. ### get\_campaign\_analytics Runs an Email Marketing analytics report. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `report` | string | Yes | Which report to run. See the table below. | | `campaignMailingId` | integer | No | Scope to one campaign mailing. | | `campaignMailingSendId` | integer | No | Scope to one campaign send. | | `dripCampaignId` | integer | No | Scope to one drip campaign. | | `trackingLinkId` | integer | No | Scope to one tracking link. | | `emailType` | string | No | Filter by email type. | | `search` | string | No | Search text. | | `orderBy` | string | No | Sort field, for example `marketing_email_id`, `sent_at`, or `subscription_list_name`. | | `order` | string | No | `asc` or `desc`. Defaults to `desc`. | | `byDate` | boolean | No | For `campaign_mailing_send_totals`: bucket results by date. | | `startDate` | string | No | Start of the date range. Pair with `endDate`. | | `endDate` | string | No | End of the date range. Pair with `startDate`. | | `dateOffset` | integer | No | For `campaign_mailing_send_totals` with `byDate`: look back this many days instead of giving `startDate`/`endDate`. | | `withStats` | boolean | No | Include summed delivery statistics columns. | | `apiKey` | string | No | Paubox API key. | | `report` value | Returns | | :- | :- | | `campaign_mailing_sends_table` | Per-send performance rows. | | `campaign_mailing_send_totals` | Aggregate totals, optionally bucketed by date. | | `campaign_mailing_deliveries_table` | Per-recipient detail for one campaign or send. | | `subscribers_by_tracking_link` | Which subscribers clicked a link. | | `tracking_links_by_unique_link` | Click counts per link. | **Example payload** ```json theme={null} { "report": "campaign_mailing_send_totals", "byDate": true, "dateOffset": 30 } ``` **Response:** returns the requested report rows. ### get\_marketing\_bulk\_job Checks the progress of an asynchronous bulk job. Bulk subscriber imports and CSV exports return a job ID (`jid` or `bid`) instead of a result; pass it here. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `bulkJobId` | string | Yes | The `bid` or `jid` returned by a bulk operation. | | `apiKey` | string | No | Paubox API key. | **Response:** returns total, pending, and failed counts for the job. ## Webhooks Manage Email API webhook endpoints that receive delivery event notifications. These tools use the same API key as the email tools, and their parameters use snake\_case. Valid `events` are `api_mail_log_delivered`, `api_mail_log_opened`, `api_mail_log_temporary_failure`, and `api_mail_log_permanent_failure`. Inbound mail subscriptions (`email.inbound.received`) are set up in the Paubox dashboard, not through these tools. See [Webhooks](/email-api/webhooks) for payloads and signature verification. ### list\_webhook\_endpoints Lists the webhook endpoints configured for the account. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `apiKey` | string | No | Paubox API key. | ### create\_webhook\_endpoint Creates a webhook endpoint. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `target_url` | string | Yes | URL that receives event notifications. | | `events` | array of strings | Yes | Events to subscribe to. At least one. | | `signing_key` | string | No | Signing key for webhook payload verification. | | `active` | boolean | No | Whether the endpoint is active. Defaults to `true`. | | `apiKey` | string | No | Paubox API key. | **Example payload** ```json theme={null} { "target_url": "https://example.com/paubox/webhooks", "events": ["api_mail_log_delivered", "api_mail_log_permanent_failure"] } ``` ### get\_webhook\_endpoint Retrieves a webhook endpoint by ID. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `endpoint_id` | integer | Yes | Webhook endpoint ID. | | `apiKey` | string | No | Paubox API key. | ### update\_webhook\_endpoint Updates a webhook endpoint. Only the fields you provide are changed. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `endpoint_id` | integer | Yes | Webhook endpoint ID. | | `target_url` | string | No | New target URL. | | `events` | array of strings | No | New set of events. | | `active` | boolean | No | Whether the endpoint is active. | | `apiKey` | string | No | Paubox API key. | ### delete\_webhook\_endpoint Deletes a webhook endpoint. | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `endpoint_id` | integer | Yes | Webhook endpoint ID. | | `apiKey` | string | No | Paubox API key. | # Node.js SDK authentication Source: https://docs.paubox.com/node-sdk/authentication Configure Paubox API credentials for the Node.js SDK with environment variables or direct configuration, plus Forms service setup and key security notes. ## Obtain your credentials The Email API service requires one credential: * **API key**: a secret token that authenticates your requests It is available in the [Paubox dashboard](https://next.paubox.com) under **API Credentials**. ## Option 1: Environment variables (recommended) Create a `.env` file in your project root: ```bash theme={null} API_KEY=YOUR_API_KEY ``` The SDK reads `API_KEY` from `process.env` but does not load `.env` files itself. Load the file with [`dotenv`](https://www.npmjs.com/package/dotenv) (`npm install dotenv`) before creating the service, then call the factory with no arguments: ```javascript theme={null} require('dotenv').config(); const pbMail = require('paubox-node'); const service = pbMail.emailService(); ``` ## Option 2: Direct configuration Pass the API key explicitly to the factory: ```javascript theme={null} const service = pbMail.emailService({ apiKey: 'YOUR_API_KEY' }); ``` The service factory throws immediately if the API key is missing, so errors surface at startup rather than at send time. The SDK sets the `Authorization` header automatically on every request: ``` Authorization: Token token=YOUR_API_KEY ``` ## Forms service `getForm` and `submitForm` are public and need no credentials: ```javascript theme={null} const formsService = pbMail.formService(); ``` All other `formService` methods need an API key with the `forms` scope, sent as `Authorization: Bearer YOUR_API_KEY`. Set `FORMS_API_KEY` in the environment, or pass it directly. `FORMS_BASE_URL` (or the `baseURL` option) overrides the default `https://api.paubox.com/v1/forms`. ```javascript theme={null} const scopedFormsService = pbMail.formService({ apiKey: 'YOUR_API_KEY' }); ``` ## Security notes * Add `.env` to your `.gitignore`; never commit credentials to source control. * In production, prefer your platform's secret management (environment variables injected by your hosting provider) over `.env` files. # Node.js SDK email client Source: https://docs.paubox.com/node-sdk/email-client Full reference for the Paubox Node.js SDK email service: building messages, sending email, tracking delivery, dynamic templates, and error handling. ## Create the service ```javascript theme={null} require('dotenv').config(); // only if you keep API_KEY in a .env file const pbMail = require('paubox-node'); // Read API_KEY from process.env const service = pbMail.emailService(); // Or pass the API key directly const service = pbMail.emailService({ apiKey: 'YOUR_API_KEY' }); ``` ## Build a message ```javascript theme={null} const message = pbMail.message({ from: 'sender@yourdomain.com', // required to: ['alice@example.com'], // required; array of recipients subject: 'Your results are ready', // optional reply_to: 'support@yourdomain.com', // optional cc: ['manager@example.com'], // optional bcc: ['audit@example.com'], // optional text_content: 'Plain text body.', // at least one of text/html required html_content: '<p>HTML body.</p>', // optional; auto base64-encoded allowNonTLS: false, // optional; default false forceSecureNotification: false, // optional; default false custom_headers: { 'X-Custom': 'value' },// optional; keys must start with X- list_unsubscribe: '<mailto:unsub@yourdomain.com>', // optional list_unsubscribe_post: 'List-Unsubscribe=One-Click', // optional attachments: [attachment] // optional; see below }); ``` ### Attachments ```javascript theme={null} const fs = require('fs'); const attachment = { fileName: 'report.pdf', contentType: 'application/pdf', content: fs.readFileSync('report.pdf').toString('base64') }; ``` ## Send a message ```javascript theme={null} const response = await service.sendMessage(message); console.log('Tracking ID:', response.sourceTrackingId); ``` ## Send bulk messages Send up to 50 messages in a single API call. Each message gets its own tracking ID. ```javascript theme={null} const messages = [ pbMail.message({ from: 'f@yourdomain.com', to: ['alice@example.com'], subject: 'Hi Alice', text_content: 'Hello Alice' }), pbMail.message({ from: 'f@yourdomain.com', to: ['bob@example.com'], subject: 'Hi Bob', text_content: 'Hello Bob' }), ]; const response = await service.sendBulkMessages(messages); for (const msg of response.messages) { console.log('Tracking ID:', msg.sourceTrackingId); } ``` ## Check delivery status ```javascript theme={null} const disposition = await service.getEmailDisposition(sourceTrackingId); for (const delivery of disposition.data.message.message_deliveries) { console.log(`${delivery.recipient} → ${delivery.status.deliveryStatus}`); } ``` Common `deliveryStatus` values: `delivered`, `delivered via secure portal`, `soft bounced`, `hard bounced`, `processing`. Opens are reported separately in `openedStatus`, which the SDK sets to `"unopened"` until the message is opened. ## Dynamic templates Templates use [Handlebars](https://handlebarsjs.com) syntax (`{{variable_name}}`). Template content can be a string, `Buffer`, or readable `Stream`. In paubox-node 1.7.1 through 2.0.0, `createDynamicTemplate`, `updateDynamicTemplate`, and `listDynamicTemplates` expect older response shapes. When the API call succeeds, the promise rejects with the parsed response instead of resolving: the template object for create and update, and `{ templates: [...] }` for list. The change is saved, so don't retry a create that rejected this way. The samples below read the result from the rejection. ### Create a template ```javascript theme={null} const fs = require('fs'); const template = await service.createDynamicTemplate( 'appointment-confirmation', fs.createReadStream('templates/appointment.html') ).catch((res) => { if (res?.id) return res; throw res; }); ``` ### List templates ```javascript theme={null} const templates = await service.listDynamicTemplates() .catch((res) => { if (Array.isArray(res?.templates)) return res.templates; throw res; }); for (const t of templates) { console.log(t.id, t.name); } ``` ### Get a template ```javascript theme={null} const template = await service.getDynamicTemplate(templateId); ``` ### Update a template Pass `null` for fields you want to leave unchanged: ```javascript theme={null} await service.updateDynamicTemplate( templateId, 'appointment-confirmation-v2', // new name, or null to keep current null // content unchanged ).catch((res) => { if (res?.id) return res; throw res; }); ``` ### Delete a template ```javascript theme={null} await service.deleteDynamicTemplate(templateId); ``` ### Send a templated message ```javascript theme={null} const message = pbMail.templatedMessage({ from: 'appointments@yourclinic.com', to: ['jane@example.com'], subject: 'Your appointment is confirmed', template_name: 'appointment-confirmation', template_values: { first_name: 'Jane', date: '2024-03-15', time: '2:00 PM' } }); const response = await service.sendTemplatedMessage(message); ``` ## Scheduled send Schedule a message for future delivery, check its status, reschedule, or cancel it. ### Schedule a message ```javascript theme={null} const scheduledAt = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(); const response = await service.scheduleMessage(message, scheduledAt); console.log('Tracking ID:', response.sourceTrackingId); console.log('Scheduled for:', response.scheduledAt); ``` `scheduledAt` must be an ISO 8601 UTC datetime string in the future and within 30 days. ### Get scheduled message status ```javascript theme={null} const status = await service.getScheduledMessage(sourceTrackingId); console.log('State:', status.state); // "pending", "processing", "sent", "failed", "cancelled" console.log('Scheduled for:', status.scheduledAt); ``` ### Reschedule a message ```javascript theme={null} const newTime = new Date(Date.now() + 2 * 24 * 60 * 60 * 1000).toISOString(); const response = await service.rescheduleMessage(sourceTrackingId, newTime); console.log('New time:', response.scheduledAt); ``` ### Cancel a scheduled message ```javascript theme={null} const response = await service.cancelScheduledMessage(sourceTrackingId); console.log('State:', response.state); // "cancelled" ``` ## Error handling All service methods return Promises and reject on API errors. Use `try/catch` in async functions: ```javascript theme={null} try { const response = await service.sendMessage(message); console.log('Sent:', response.sourceTrackingId); } catch (err) { console.error('Send failed:', err.message); } ``` # Node.js SDK forms client Source: https://docs.paubox.com/node-sdk/forms-client Retrieve Paubox Form schemas and submit form responses using the Node.js SDK. `getForm` and `submitForm` do not require API credentials. The form management methods require an API key with the `forms` scope (see [Manage forms](#manage-forms)). Forms are identified by a UUID that you obtain from the Paubox dashboard. ## Create the service ```javascript theme={null} const pbMail = require('paubox-node'); const formsService = pbMail.formService(); ``` ## Get a form Retrieve a form's metadata, field schema, and rendered HTML/CSS: ```javascript theme={null} const form = await formsService.getForm('your-form-uuid'); console.log('Title:', form.title); console.log('HTML:', form.form_html); ``` Key fields in the response: | Field | Description | | - | - | | `title` | Display name of the form | | `form_json` | Parsed field schema | | `form_html` | Rendered HTML for embedding | | `form_css` | Associated stylesheet | | `active` | Whether the form is accepting submissions | | `submission_count` | Number of submissions received | The Promise rejects with a 404 error if the form UUID is invalid. ## Submit a form ```javascript theme={null} await formsService.submitForm('your-form-uuid', { first_name: 'Jane', last_name: 'Smith', email: 'jane@example.com' }); // Resolves to null on success (HTTP 201) ``` ### Submitting with file attachments The maximum total request size is 250 MB. ```javascript theme={null} const fs = require('fs'); const attachments = [ { name: 'consent.pdf', content: fs.readFileSync('consent.pdf').toString('base64') } ]; await formsService.submitForm( 'your-form-uuid', { first_name: 'Jane' }, attachments ); ``` Each attachment is an object with two fields: | Field | Description | | - | - | | `name` | File name including extension | | `content` | Base64-encoded file content | ## Manage forms These methods need a `forms`-scoped API key, sent as `Authorization: Bearer YOUR_API_KEY`. Create the service with `pbMail.formService({ apiKey: 'YOUR_API_KEY' })`, or set `FORMS_API_KEY` in the environment. Without a key they throw an error. | Method | Description | | - | - | | `listForms(params)` | List forms; `params.customer_id` is required | | `createForm(formAttributes)` | Create a form | | `getFormById(formId)` | Get any of your forms, including archived and inactive ones | | `updateForm(formId, updates)` | Update a form | | `archiveForm(formId)` / `unarchiveForm(formId)` | Archive or restore a form | | `copyForm(formId, title)` | Copy a form under a new title | | `getFormStats(customerId)` | Form and submission counts; `customerId` is optional | | `listSubmissions(formId, params)` | List a form's submissions | | `exportSubmissionsCsv(formId, submissionId)` | Export all submissions, or one when `submissionId` is set, as CSV | | `exportSubmissionPdf(formId, submissionId)` | Export one submission as PDF | ```javascript theme={null} const formsAdmin = pbMail.formService({ apiKey: 'YOUR_API_KEY' }); const list = await formsAdmin.listForms({ customer_id: 12345, active: true, items: 25 }); list.results.forEach(f => console.log(`${f.id}: ${f.title}`)); ``` ## Error handling ```javascript theme={null} try { const form = await formsService.getForm('your-form-uuid'); await formsService.submitForm('your-form-uuid', formData); } catch (err) { console.error('Forms error:', err.message); } ``` The Promise rejects on HTTP 400 (bad request) and 404 (form not found). # Paubox Node.js SDK Source: https://docs.paubox.com/node-sdk/index Send HIPAA compliant email and submit Paubox Forms from Node.js applications using the official Paubox Node.js SDK. The Paubox Node.js SDK is the official JavaScript client library for the [Paubox Email API](/email-api) and [Paubox Forms](/forms). All service methods return Promises, making them compatible with `async/await` and promise chains. ```bash theme={null} npm install --save paubox-node ``` ## What you can do * Send encrypted, HIPAA compliant email to one or more recipients * Send batches of up to 50 messages in a single API call * Create, update, and delete dynamic Handlebars templates * Send templated messages with per-message variable substitution * Track delivery status and engagement per recipient * Schedule, reschedule, and cancel messages * Retrieve Paubox Form schemas and submit form responses with file attachments * Manage forms, submissions, and exports with a forms-scoped API key * Manage receiving domains and mailboxes, and read inbound email * Manage webhook endpoints ## Requirements * Node.js v22 or later ## Get started > [card] [Quickstart](/node-sdk/quickstart) > > Install, configure credentials, and send your first email in minutes. > [card] [Authentication](/node-sdk/authentication) > > Set up your API key via environment variables or direct config. > [card] [Email client](/node-sdk/email-client) > > Full reference for sending email, managing templates, and tracking delivery. > [card] [Forms client](/node-sdk/forms-client) > > Retrieve form schemas and submit responses. > [card] [Receiving client](/node-sdk/receiving-client) > > Manage receiving domains and mailboxes, and read inbound email. > [card] [Webhook client](/node-sdk/webhook-client) > > Create and manage webhook endpoints. # Node.js SDK quickstart Source: https://docs.paubox.com/node-sdk/quickstart Install the Paubox Node.js SDK and send your first HIPAA compliant email in minutes. **1. Install the SDK** ```bash theme={null} npm install --save paubox-node dotenv ``` **2. Set your API key** Create a `.env` file in your project root: ```bash theme={null} API_KEY=YOUR_API_KEY ``` The SDK reads `API_KEY` from `process.env` but does not load `.env` files itself, so the sample below loads it with `dotenv`. To obtain your API key, see [Authentication](/node-sdk/authentication). **3. Send your first email** Create `send.js`: ```javascript theme={null} require('dotenv').config(); const pbMail = require('paubox-node'); async function main() { const service = pbMail.emailService(); const message = pbMail.message({ from: 'sender@yourdomain.com', to: ['recipient@example.com'], subject: 'Your first Paubox email', text_content: 'This message was sent with the Paubox Node.js SDK.' }); const response = await service.sendMessage(message); console.log('Sent. Tracking ID:', response.sourceTrackingId); } main().catch(console.error); ``` Run it: ```bash theme={null} node send.js ``` ``` Sent. Tracking ID: abc123-def456-... ``` **4. Check delivery status** ```javascript theme={null} const disposition = await service.getEmailDisposition(response.sourceTrackingId); for (const delivery of disposition.data.message.message_deliveries) { console.log(`${delivery.recipient} → ${delivery.status.deliveryStatus}`); } ``` ``` recipient@example.com → delivered ``` ## Next steps * [Email client](/node-sdk/email-client): bulk send, attachments, dynamic templates, error handling * [Forms client](/node-sdk/forms-client): retrieve form schemas and submit responses # Node.js SDK receiving client Source: https://docs.paubox.com/node-sdk/receiving-client Full reference for the Paubox Node.js SDK receiving API: managing domains, mailboxes, and retrieving inbound email. The receiving methods are on the same `emailService` you use to send email. ```javascript theme={null} const pbMail = require('paubox-node'); const service = pbMail.emailService({ apiKey: 'YOUR_API_KEY' }); ``` ## Domains ### List domains ```javascript theme={null} const domains = await service.listReceivingDomains(); domains.data.forEach(d => console.log(d.domain)); ``` ### Create a domain ```javascript theme={null} const domain = await service.createReceivingDomain('support'); console.log(domain.data.domain); // support.inbound.paubox.email ``` Pass `null` or omit the argument to auto-generate a slug. ### Get a domain ```javascript theme={null} const domain = await service.getReceivingDomain(1); ``` ### Delete a domain ```javascript theme={null} await service.deleteReceivingDomain(1); ``` ## Mailboxes ### List mailboxes ```javascript theme={null} const mailboxes = await service.listReceivingMailboxes(domainId); ``` ### Create a mailbox ```javascript theme={null} const mailbox = await service.createReceivingMailbox( domainId, 'intake', 'SecurePass123!' ); console.log(mailbox.data.email_address); ``` Pass a fourth argument for `quotaBytes`. ### Get a mailbox ```javascript theme={null} const mailbox = await service.getReceivingMailbox(domainId, mailboxId); ``` ### Delete a mailbox ```javascript theme={null} await service.deleteReceivingMailbox(domainId, mailboxId); ``` ## Emails ### List received emails ```javascript theme={null} const emails = await service.listReceivedEmails({ limit: 10 }); emails.data.forEach(e => console.log(`${e.email_id}: ${e.subject}`)); // Cursor pagination; also accepts before, search, sort, and ascending const next = await service.listReceivedEmails({ after: emails.data[emails.data.length - 1].email_id }); ``` ### Get a received email ```javascript theme={null} const email = await service.getReceivedEmail(emailId); console.log(email.data.text_body); ``` ### Download an attachment Email and attachment IDs are UUIDs. Pass the attachment's `id` from the email's `attachments` array. The method resolves to `{ content, content_type, filename }`, where `content` is a `Buffer`: ```javascript theme={null} const fs = require('fs'); const path = require('path'); const { id } = email.data.attachments[0]; const attachment = await service.getReceivedEmailAttachment(email.data.email_id, id); fs.writeFileSync(path.basename(attachment.filename || 'attachment'), attachment.content); ``` # Node.js SDK webhook client Source: https://docs.paubox.com/node-sdk/webhook-client Create, list, get, update, and delete Paubox webhook endpoints with the Node.js SDK to receive Email API and Forms events. > [!NOTE] > > Webhook endpoint methods require `paubox-node` 2.0.0 or later. They are on `webhookService`, not on `emailService`. `webhookService` manages webhook endpoints through the Paubox webhooks service at `https://api.paubox.com/v1/webhooks`. It sends a scoped API key as `Authorization: Bearer YOUR_API_KEY`. The key's scopes decide which events it can subscribe to. ## Create the service ```javascript theme={null} const paubox = require('paubox-node'); const webhooks = paubox.webhookService({ apiKey: 'YOUR_API_KEY' }); ``` When `apiKey` is omitted, the service reads `WEBHOOKS_API_KEY` from `process.env`. Pass `baseURL` or set `WEBHOOKS_BASE_URL` to override the base URL. Every method rejects before sending a request if no key is set. ## Events | Event | Required scope | Fires when | | - | - | - | | `api_mail_log_delivered` | `email_api` | An Email API message is delivered | | `api_mail_log_opened` | `email_api` | A delivered message is opened | | `api_mail_log_temporary_failure` | `email_api` | Delivery fails temporarily | | `api_mail_log_permanent_failure` | `email_api` | Delivery fails permanently | | `email.inbound.received` | `email_api`, with no sender-domain limit | Inbound mail is received | | `forms.submission.created` | `forms` | A form submission is received | The SDK doesn't check event names. The API returns 422 for an unknown event and 403 for an event the key isn't scoped for. Email API keys created in the Paubox Dashboard are limited to a sender domain, so subscribe to inbound mail in the Paubox Dashboard under [Settings > Webhooks](https://next.paubox.com/settings/webhooks). For payloads and signature verification, see [Webhooks](/email-api/webhooks). ## List webhook endpoints ```javascript theme={null} const result = await webhooks.listWebhookEndpoints({ page: 1, items: 50 }); for (const endpoint of result.data) { console.log(endpoint.id, endpoint.target_url, endpoint.status); } console.log(result.page_info.count); ``` The argument is optional. The result is `{ data, page_info }`; `page_info.count` is the total number of endpoints, not the length of this page. Endpoints carrying an event the key isn't scoped for are left out. ## Create a webhook endpoint ```javascript theme={null} const endpoint = await webhooks.createWebhookEndpoint({ target_url: 'https://example.com/webhooks/paubox', events: ['api_mail_log_delivered', 'api_mail_log_opened'], }); console.log(endpoint.id); console.log(endpoint.signing_secret); ``` `target_url` must be an `https` URL that doesn't point at a private or internal address. Each endpoint has `id` (a UUID), `target_url`, `status` (`active` or `disabled`), `events`, `created_at`, and `updated_at`. `signing_secret` is returned only by this call; store it when you create the endpoint. To replace a lost secret, delete the endpoint and create a new one. ## Get a webhook endpoint ```javascript theme={null} const endpoint = await webhooks.getWebhookEndpoint('2ec66c21-bf48-48eb-8d28-f80b2d6b77c7'); ``` ## Update a webhook endpoint ```javascript theme={null} const endpoint = await webhooks.updateWebhookEndpoint('2ec66c21-bf48-48eb-8d28-f80b2d6b77c7', { status: 'disabled', }); ``` Pass any of `target_url`, `status` (`active` or `disabled`), and `events`. Only the fields you pass are sent. `events` replaces the endpoint's event list. ## Delete a webhook endpoint ```javascript theme={null} await webhooks.deleteWebhookEndpoint('2ec66c21-bf48-48eb-8d28-f80b2d6b77c7'); ``` The Promise resolves to `undefined`. ## Error handling ```javascript theme={null} try { await webhooks.createWebhookEndpoint({ target_url: 'https://example.com/webhooks/paubox', events: ['api_mail_log_delivered'], }); } catch (err) { console.error(err.status, err.message); } ``` A non-2xx response rejects with an `Error` whose `message` is the API's error text and whose `status` is the HTTP status. Creating a second endpoint for the same `target_url` returns 422, and an ID that isn't on your account returns 404. An ID that isn't a UUID rejects before any request is sent. # Perl SDK authentication Source: https://docs.paubox.com/perl-sdk/authentication Configure Paubox API credentials for the Perl SDK with a config.cfg file, plus Forms client setup and security notes for handling your API key. ## Obtain your API key The Email API client requires one credential: * **API key**: a secret token that authenticates your requests It is available in the [Paubox dashboard](https://next.paubox.com) under **API Credentials**. ## Create a config.cfg file Create a `config.cfg` file in your project directory: ``` apiKey = YOUR_API_KEY ``` The key name is case-sensitive: `API_KEY` is not recognized. The SDK reads this file automatically via `Config::General` when you instantiate the client; no constructor arguments are needed: ```perl theme={null} my $service = Paubox_Email_SDK->new(); ``` `config.cfg` is read from the current working directory. The constructor dies immediately if `apiKey` is missing from the config file, so credential errors are caught at startup. The SDK sets the `Authorization` header on every request: ``` Authorization: Token token=YOUR_API_KEY ``` ## Forms client `getForm` and `submitForm` are public and need no credentials: ```perl theme={null} my $forms = Paubox_Forms_SDK->new(); ``` All other `Paubox_Forms_SDK` methods need an API key with the `forms` scope, sent as `Authorization: Bearer YOUR_API_KEY`. Pass it to the constructor, or set `FORMS_API_KEY` in `config.cfg`: ```perl theme={null} my $forms = Paubox_Forms_SDK->new('apiKey' => 'YOUR_API_KEY'); ``` ``` FORMS_API_KEY = YOUR_API_KEY ``` ## Security notes * Do not commit `config.cfg` to source control. Add it to your `.gitignore`. * The SDK does not expose credentials in error messages or logs. # Perl SDK email client Source: https://docs.paubox.com/perl-sdk/email-client Full reference for the Paubox Perl SDK Email API client: building messages, sending email, tracking delivery, and error handling. ## Instantiation ```perl theme={null} my $service = Paubox_Email_SDK->new(); ``` Credentials are read automatically from `config.cfg` (see [Authentication](/perl-sdk/authentication)). The constructor dies if `apiKey` is missing. ## Building a message Messages are created with a single constructor call using named parameters: ```perl theme={null} my $msg = Paubox_Email_SDK::Message->new( 'from' => 'sender@yourdomain.com', # required 'to' => ['alice@example.com'], # required; arrayref 'subject' => 'Your results are ready', # required 'text_content' => 'Plain text body.', # at least one required 'html_content' => '<p>HTML body.</p>', # optional; auto base64-encoded 'replyTo' => 'support@yourdomain.com', # optional 'cc' => ['manager@example.com'], # optional; arrayref 'bcc' => ['audit@example.com'], # optional; arrayref 'allowNonTLS' => 'false', # optional; "true"/"false" 'forceSecureNotification' => 'true', # optional; "true"/"false" 'attachments' => [$attachment], # optional; arrayref of hashrefs ); ``` Pass `allowNonTLS` as the string `'true'` or `'false'`. If you leave it out, the SDK sends the number `0`, which the scheduling endpoint rejects with a 400 error, so `scheduleMessage` fails unless you set it. ### Attachments Each attachment is a hashref with three keys. Use `MIME::Base64` to encode the file content: ```perl theme={null} use MIME::Base64; use String::Util qw(trim); my $attachment = { fileName => 'report.pdf', contentType => 'application/pdf', content => trim(encode_base64(do { local $/; open my $fh, '<:raw', 'report.pdf' or die $!; <$fh> })), }; my $msg = Paubox_Email_SDK::Message->new( 'from' => 'sender@yourdomain.com', 'to' => ['alice@example.com'], 'subject' => 'Report attached', 'text_content'=> 'See attachment.', 'attachments' => [$attachment], ); ``` `String::Util::trim` removes the trailing newline that `encode_base64` appends. ## Send a message ```perl theme={null} my $response = $service->sendMessage($msg); ``` The response is a raw JSON string. Decode it to access fields: ```perl theme={null} use JSON; my $json = decode_json($response); print "Tracking ID: " . $json->{sourceTrackingId} . "\n"; ``` ## Check delivery status ```perl theme={null} my $disposition = $service->getEmailDisposition($sourceTrackingId); my $json = decode_json($disposition); for my $delivery (@{ $json->{data}{message}{message_deliveries} }) { print $delivery->{recipient} . " -> " . $delivery->{status}{deliveryStatus} . "\n"; } ``` Common `deliveryStatus` values: `delivered`, `delivered via secure portal`, `soft bounced`, `hard bounced`, `processing`. Opens are reported separately in `openedStatus`, which the SDK sets to `"unopened"` until the message is opened. ## Scheduled send Schedule a message for future delivery, check its status, reschedule, or cancel it. ### Schedule a message ```perl theme={null} use POSIX qw(strftime); my $scheduledAt = strftime('%Y-%m-%dT%H:%M:%SZ', gmtime(time + 24 * 60 * 60)); my $response = $service->scheduleMessage($msg, $scheduledAt); my $json = decode_json($response); print "Tracking ID: " . $json->{sourceTrackingId} . "\n"; print "Scheduled for: " . $json->{scheduledAt} . "\n"; ``` `scheduledAt` must be an ISO 8601 UTC datetime string in the future and within 30 days. ### Get scheduled message status ```perl theme={null} my $response = $service->getScheduledMessage($sourceTrackingId); my $json = decode_json($response); print "State: " . $json->{state} . "\n"; # "pending", "processing", "sent", "failed", "cancelled" print "Scheduled for: " . $json->{scheduledAt} . "\n"; ``` ### Reschedule a message ```perl theme={null} my $newTime = strftime('%Y-%m-%dT%H:%M:%SZ', gmtime(time + 2 * 24 * 60 * 60)); my $response = $service->rescheduleMessage($sourceTrackingId, $newTime); my $json = decode_json($response); print "New time: " . $json->{scheduledAt} . "\n"; ``` ### Cancel a scheduled message ```perl theme={null} my $response = $service->cancelScheduledMessage($sourceTrackingId); my $json = decode_json($response); print "State: " . $json->{state} . "\n"; # "cancelled" ``` ## Error handling Methods die when a response cannot be interpreted. An API error response that contains an `errors` key is returned as JSON, not thrown, so check for it as well as wrapping calls in `eval`: ```perl theme={null} use JSON; my $response = eval { $service->sendMessage($msg) }; if ($@) { print "Error: $@\n"; } else { my $json = decode_json($response); if ($json->{errors}) { print "API error: $_->{title}\n" for @{ $json->{errors} }; } else { print "Sent: $json->{sourceTrackingId}\n"; } } ``` # Perl SDK forms client Source: https://docs.paubox.com/perl-sdk/forms-client Retrieve Paubox Form schemas and submit form responses using the Perl SDK. `getForm` and `submitForm` do not require API credentials. The form management methods require an API key with the `forms` scope (see [Manage forms](#manage-forms)). Forms are identified by a UUID that you obtain from the Paubox dashboard. ## Instantiation ```perl theme={null} use Paubox_Forms_SDK; my $forms = Paubox_Forms_SDK->new(); ``` ## Get a form Retrieve a form's metadata, field schema, and rendered HTML/CSS: ```perl theme={null} my $response = $forms->getForm("your-form-uuid"); ``` The response is a raw JSON string. Decode it to access fields: ```perl theme={null} use JSON; my $form = decode_json($response); print "Title: " . $form->{title} . "\n"; print "HTML: " . $form->{form_html} . "\n"; ``` Key fields in the response: | Field | Description | | - | - | | `title` | Display name of the form | | `form_json` | Parsed field schema | | `form_html` | Rendered HTML for embedding | | `form_css` | Associated stylesheet | | `active` | Whether the form is accepting submissions | `getForm` dies if the form UUID is invalid or the form is not found. ## Submit a form ```perl theme={null} my $result = $forms->submitForm( "your-form-uuid", { first_name => "Jane", last_name => "Smith", email => "jane@example.com" } ); # $result is an empty string on success (HTTP 201) ``` `submitForm` dies if the form ID or form data is invalid, or if the response has an `errors` key. Other API errors are returned rather than thrown: `$result` holds the error body, such as `{"message":"Attachment content is not valid base64"}`. Treat any non-empty `$result` as a failed submission. ### Submitting with file attachments The maximum total request size is 250 MB. ```perl theme={null} use MIME::Base64; open(my $fh, '<:raw', 'consent.pdf') or die "Cannot open file: $!"; local $/; my $encoded = encode_base64(<$fh>, ''); close($fh); my $result = $forms->submitForm( "your-form-uuid", { first_name => "Jane" }, [ { name => "consent.pdf", content => $encoded } ] ); ``` Each attachment in the arrayref is a hashref with two keys: | Key | Description | | - | - | | `name` | File name including extension | | `content` | Base64-encoded file content | Pass `''` as the second argument to `encode_base64`. By default it adds a line break every 76 characters, and the API rejects base64 that contains line breaks. ## Manage forms These methods need a `forms`-scoped API key, sent as `Authorization: Bearer YOUR_API_KEY`. Create the client with `Paubox_Forms_SDK->new('apiKey' => 'YOUR_API_KEY')`, or set `FORMS_API_KEY` in `config.cfg`. Without a key they die. Call them as methods on the object. | Method | Description | | - | - | | `listForms(\%params)` | List forms; `customer_id` is required | | `createForm(\%attrs)` | Create a form | | `getFormById($formId)` | Get any of your forms, including archived and inactive ones | | `updateForm($formId, \%updates)` | Update a form | | `archiveForm($formId)` / `unarchiveForm($formId)` | Archive or restore a form | | `copyForm($formId, $newTitle)` | Copy a form under a new title | | `getFormStats(\%params)` | Form and submission counts; `customer_id` is optional | | `listFormSubmissions($formId, \%params)` | List a form's submissions | | `getSubmissionsCsv($formId, $submissionId)` | Export all submissions, or one when `$submissionId` is set, as CSV | | `getSubmissionPdf($formId, $submissionId)` | Export one submission as PDF | ```perl theme={null} use JSON; my $formsAdmin = Paubox_Forms_SDK->new('apiKey' => 'YOUR_API_KEY'); my $list = decode_json($formsAdmin->listForms({ customer_id => 12345, active => 1, items => 25 })); print "$_->{id}: $_->{title}\n" for @{ $list->{results} }; ``` ## Error handling Wrap calls in `eval` to catch the errors that die, and check `submitForm`'s return value for the ones it returns: ```perl theme={null} my $result = eval { my $form = $forms->getForm("your-form-uuid"); $forms->submitForm("your-form-uuid", \%formData); }; if ($@) { print "Error: $@\n"; } elsif ($result ne '') { print "Submission failed: $result\n"; } ``` # Paubox Perl SDK Source: https://docs.paubox.com/perl-sdk/index Send HIPAA compliant email and submit Paubox Forms from Perl applications using the official Paubox Perl SDK. The Paubox Perl SDK is the official Perl client library for the [Paubox Email API](/email-api) and [Paubox Forms](/forms). Install it from the GitHub source and send encrypted, HIPAA compliant email with a few lines of Perl. ```bash theme={null} git clone https://github.com/Paubox/paubox-perl.git cd paubox-perl cpanm . ``` > [!NOTE] > > The `Paubox_Email_SDK` release on CPAN is version 1.2 from 2019. It only supports sending a message and checking its disposition, and it requires an `apiUsername` in `config.cfg`. Install from the GitHub source as shown above to use the features documented here. ## What you can do * Send encrypted, HIPAA compliant email to one or more recipients * Add CC, BCC, attachments, and HTML or plain-text content * Track delivery status and engagement per recipient * Schedule, reschedule, and cancel messages * Retrieve Paubox Form schemas and submit form responses with file attachments * Manage forms, submissions, and exports with a forms-scoped API key * Manage receiving domains and mailboxes, and read inbound email * Manage webhook endpoints ## Requirements * Perl * [cpanminus](https://metacpan.org/pod/App::cpanminus) (`cpanm`) * Dependencies installed automatically: `JSON`, `Config::General`, `REST::Client`, `TryCatch`, `String::Util`, `MIME::Base64`, `URI` ## Get started > [card] [Quickstart](/perl-sdk/quickstart) > > Install, configure credentials, and send your first email in minutes. > [card] [Authentication](/perl-sdk/authentication) > > Set up your API key via a config.cfg file. > [card] [Email client](/perl-sdk/email-client) > > Full reference for sending email and checking delivery status. > [card] [Forms client](/perl-sdk/forms-client) > > Retrieve form schemas and submit responses. > [card] [Receiving client](/perl-sdk/receiving-client) > > Manage receiving domains and mailboxes, and read inbound email. > [card] [Webhook client](/perl-sdk/webhook-client) > > Create and manage webhook endpoints. # Perl SDK quickstart Source: https://docs.paubox.com/perl-sdk/quickstart Install the Paubox Perl SDK and send your first HIPAA compliant email in minutes. **1. Install the SDK** Install from the GitHub source using cpanminus: ```bash theme={null} git clone https://github.com/Paubox/paubox-perl.git cd paubox-perl cpanm . ``` The CPAN release (1.2, from 2019) predates most of this API and requires an `apiUsername`, so install from source. **2. Set your credentials** Create a `config.cfg` file in your project directory: ``` apiKey = YOUR_API_KEY ``` The SDK reads this file from the current working directory when you call `new()`. The key name is case-sensitive. To obtain credentials, see [Authentication](/perl-sdk/authentication). **3. Send your first email** Create a file `send.pl`: ```perl theme={null} use Paubox_Email_SDK; my $msg = Paubox_Email_SDK::Message->new( 'from' => 'sender@yourdomain.com', 'to' => ['recipient@example.com'], 'subject' => 'Your first Paubox email', 'text_content' => 'This message was sent with the Paubox Perl SDK.', ); my $service = Paubox_Email_SDK->new(); my $response = $service->sendMessage($msg); print "Response: $response\n"; ``` Run it: ```bash theme={null} perl send.pl ``` The response is a JSON string containing `sourceTrackingId`: ```json theme={null} {"sourceTrackingId":"abc123-def456-...","customHeaders":{},"data":"Service OK"} ``` **4. Check delivery status** Pass the tracking ID to `getEmailDisposition`: ```perl theme={null} use JSON; my $json = decode_json($response); my $tracking = $json->{sourceTrackingId}; my $disposition = $service->getEmailDisposition($tracking); print "Disposition: $disposition\n"; ``` The response JSON includes `message_deliveries` with per-recipient status. ## Next steps * [Email client](/perl-sdk/email-client): add HTML, attachments, CC/BCC, and handle errors * [Forms client](/perl-sdk/forms-client): retrieve form schemas and submit responses # Perl SDK receiving client Source: https://docs.paubox.com/perl-sdk/receiving-client Full reference for the Paubox Perl SDK receiving API: managing domains, mailboxes, and retrieving inbound email. The receiving methods are on the same `Paubox_Email_SDK` object you use to send email. Call them as methods on an object created with `new()`, which loads `apiKey` from `config.cfg`: ```perl theme={null} use Paubox_Email_SDK; my $sdk = Paubox_Email_SDK->new(); ``` Each method returns the raw JSON response as a string. ## Domains ### List domains ```perl theme={null} my $json = $sdk->listReceivingDomains(); ``` ### Create a domain ```perl theme={null} my $json = $sdk->createReceivingDomain({ slug => 'support' }); ``` Pass an empty hashref or no argument to auto-generate a slug. ### Get a domain ```perl theme={null} my $json = $sdk->getReceivingDomain(1); ``` ### Delete a domain ```perl theme={null} $sdk->deleteReceivingDomain(1); ``` ## Mailboxes ### List mailboxes ```perl theme={null} my $json = $sdk->listMailboxes($domain_id); ``` ### Create a mailbox ```perl theme={null} my $json = $sdk->createMailbox($domain_id, { name => 'intake', password => 'SecurePass123!', }); ``` Add `quota_bytes` to the hashref to set a storage quota. ### Get a mailbox ```perl theme={null} my $json = $sdk->getMailbox($domain_id, $mailbox_id); ``` ### Delete a mailbox ```perl theme={null} $sdk->deleteMailbox($domain_id, $mailbox_id); ``` ## Emails ### List received emails ```perl theme={null} my $json = $sdk->listReceivedEmails({ limit => 10 }); ``` `after` and `before` cursors are also accepted for pagination, along with `search`, `sort`, and `ascending`. ### Get a received email ```perl theme={null} my $json = $sdk->getReceivedEmail($email_id); ``` ### Download an attachment Email and attachment IDs are UUIDs. Pass the attachment's `id` from the email's `attachments` array. The method returns the raw attachment bytes and dies on a non-2xx response. ```perl theme={null} my $data = $sdk->getReceivedEmailAttachment($email_id, $attachment_id); ``` # Perl SDK webhook client Source: https://docs.paubox.com/perl-sdk/webhook-client Create, list, get, update, and delete Paubox webhook endpoints with the Perl SDK to receive Email API and Forms events. > [!NOTE] > > Webhook endpoint methods require SDK 3.0.0 or later (the `Paubox_Webhooks_SDK` module itself reports version 2.3.1 in that release). They are on `Paubox_Webhooks_SDK`, not on the `Paubox_Email_SDK` object you use to send email. `Paubox_Webhooks_SDK` manages webhook endpoints through the Paubox webhooks service at `https://api.paubox.com/v1/webhooks`. It sends a scoped API key as `Authorization: Bearer YOUR_API_KEY`. The key's scopes decide which events it can subscribe to. ## Create the client ```perl theme={null} use Paubox_Webhooks_SDK; my $webhooks = Paubox_Webhooks_SDK->new('apiKey' => 'YOUR_API_KEY'); ``` When `apiKey` is omitted, `new()` reads `WEBHOOKS_API_KEY` from `config.cfg` in the working directory: ``` WEBHOOKS_API_KEY = YOUR_API_KEY ``` Every method dies before sending a request if no key is set. The base URL can't be changed. ## Events | Event | Required scope | Fires when | | - | - | - | | `api_mail_log_delivered` | `email_api` | An Email API message is delivered | | `api_mail_log_opened` | `email_api` | A delivered message is opened | | `api_mail_log_temporary_failure` | `email_api` | Delivery fails temporarily | | `api_mail_log_permanent_failure` | `email_api` | Delivery fails permanently | | `email.inbound.received` | `email_api`, with no sender-domain limit | Inbound mail is received | | `forms.submission.created` | `forms` | A form submission is received | The SDK doesn't check event names. The API returns 422 for an unknown event and 403 for an event the key isn't scoped for. Email API keys created in the Paubox Dashboard are limited to a sender domain, so subscribe to inbound mail in the Paubox Dashboard under [Settings > Webhooks](https://next.paubox.com/settings/webhooks). For payloads and signature verification, see [Webhooks](/email-api/webhooks). ## List webhook endpoints ```perl theme={null} use JSON; my $result = from_json($webhooks->listWebhookEndpoints({ page => 1, items => 50 })); foreach my $endpoint (@{ $result->{'data'} }) { print "$endpoint->{'id'} $endpoint->{'target_url'} $endpoint->{'status'}\n"; } print $result->{'page_info'}{'count'}, "\n"; ``` Every method except `deleteWebhookEndpoint` returns the raw JSON response body; decode it with `from_json`. The hashref argument is optional. `page_info.count` is the total number of endpoints, not the length of this page. Endpoints carrying an event the key isn't scoped for are left out. ## Create a webhook endpoint ```perl theme={null} my $created = from_json($webhooks->createWebhookEndpoint({ target_url => 'https://example.com/webhooks/paubox', events => ['api_mail_log_delivered', 'api_mail_log_opened'], })); print $created->{'data'}{'id'}, "\n"; print $created->{'data'}{'signing_secret'}, "\n"; ``` `target_url` must be an `https` URL that doesn't point at a private or internal address. Responses for a single endpoint wrap it in `data`. Each endpoint has `id` (a UUID), `target_url`, `status` (`active` or `disabled`), `events`, `created_at`, and `updated_at`. `signing_secret` is returned only by this call; store it when you create the endpoint. To replace a lost secret, delete the endpoint and create a new one. ## Get a webhook endpoint ```perl theme={null} my $endpoint = from_json($webhooks->getWebhookEndpoint('2ec66c21-bf48-48eb-8d28-f80b2d6b77c7'))->{'data'}; ``` ## Update a webhook endpoint ```perl theme={null} my $updated = from_json($webhooks->updateWebhookEndpoint('2ec66c21-bf48-48eb-8d28-f80b2d6b77c7', { status => 'disabled', }))->{'data'}; ``` Pass any of `target_url`, `status` (`active` or `disabled`), and `events`. Only the keys you pass are sent. `events` replaces the endpoint's event list. ## Delete a webhook endpoint ```perl theme={null} $webhooks->deleteWebhookEndpoint('2ec66c21-bf48-48eb-8d28-f80b2d6b77c7'); ``` Returns `1`. ## Error handling ```perl theme={null} eval { $webhooks->createWebhookEndpoint({ target_url => 'https://example.com/webhooks/paubox', events => ['api_mail_log_delivered'], }); }; print "Error: $@" if $@; ``` Methods `die` on a non-2xx response with the API's error text; the HTTP status isn't included unless the response body is empty, in which case the message is "Request failed with HTTP status N." Creating a second endpoint for the same `target_url` returns 422, and an ID that isn't on your account returns 404. An ID that isn't a UUID dies before any request is sent. # PHP SDK authentication Source: https://docs.paubox.com/php-sdk/authentication Configure your Paubox API key for the PHP SDK with a .env file, plus Forms client setup and security notes for handling the key. ## Obtain your API key The Email API client requires one credential: * **API key**: a secret token that authenticates your requests It is available in the [Paubox dashboard](https://next.paubox.com) under **API Credentials**. ## Create a .env file Add your API key to a `.env` file at your project root: ```bash theme={null} PAUBOX_API_KEY=YOUR_API_KEY ``` The SDK reads `PAUBOX_API_KEY` with `getenv()` but does not load `.env` files. Load it with `vlucas/phpdotenv` (installed with the SDK) before creating the client; no constructor arguments are needed: ```php theme={null} require_once __DIR__ . '/vendor/autoload.php'; Dotenv\Dotenv::createUnsafeImmutable(__DIR__)->load(); $paubox = new Paubox\Paubox(); ``` Any other way of setting the `PAUBOX_API_KEY` environment variable also works. `Paubox\Paubox` sets this `Authorization` header on every request: ``` Authorization: Bearer YOUR_API_KEY ``` `Paubox\PauboxReceiving` takes the same key as a constructor argument, or reads `PAUBOX_API_KEY` when it is omitted. It sends it in the legacy `Authorization: Token token=YOUR_API_KEY` format, which the Email API also accepts. `Paubox\PauboxWebhooks` needs a scoped API key, sent as `Authorization: Bearer YOUR_API_KEY`. Pass it to the constructor, or set `PAUBOX_WEBHOOKS_API_KEY`. See [Webhook client](/php-sdk/webhook-client). ## Forms client `getForm` and `submitForm` on `Paubox\PauboxForms` require no credentials. Form submissions are associated with the form ID, not an API key. ```php theme={null} $forms = new Paubox\PauboxForms(); ``` The form management methods (for example `listForms`, `createForm`, and `listSubmissions`) require a scoped API key with the `forms` scope. It can be the same key as `PAUBOX_API_KEY` if that key also has the `forms` scope. Pass it to the constructor or set `PAUBOX_FORMS_API_KEY`: ```php theme={null} $forms = new Paubox\PauboxForms('YOUR_FORMS_API_KEY'); ``` ## Security notes * Never commit `.env` files to source control. Add `.env` to your `.gitignore`. * The SDK does not expose credentials in error messages or logs. # PHP SDK email client Source: https://docs.paubox.com/php-sdk/email-client Full reference for the Paubox PHP SDK Email API client: building messages, sending email, tracking delivery, and error handling. ## Instantiation ```php theme={null} $paubox = new Paubox\Paubox(); ``` Your API key is read from the `PAUBOX_API_KEY` environment variable. The SDK does not load `.env` files itself (see [Authentication](/php-sdk/authentication)). No constructor arguments are needed. ## Building a message A message is assembled from three objects (`Header`, `Content`, and `Message`) plus optional `Attachment` objects. ### Header ```php theme={null} $header = new Paubox\Mail\Header(); $header->setSubject("Your results are ready"); // required $header->setFrom("sender@yourdomain.com"); // required $header->setReplyTo("support@yourdomain.com"); // optional ``` ### Content ```php theme={null} $content = new Paubox\Mail\Content(); $content->setPlainText("Plain text body."); // at least one required $content->setHtmlText("<p>HTML body.</p>"); // optional; auto base64-encoded by SDK ``` ### Message ```php theme={null} $message = new Paubox\Mail\Message(); $message->setHeader($header); // required $message->setContent($content); // required $message->setRecipients(["alice@example.com"]); // required $message->setCc(["manager@example.com"]); // optional $message->setBcc(["audit@example.com"]); // optional $message->setAttachments([$attachment]); // optional; see below $message->setAllowNonTLS(false); // optional; default false $message->setForceSecureNotification("true"); // optional ``` ### Attachments ```php theme={null} $attachment = new Paubox\Mail\Attachment(); $attachment->setFileName("report.pdf"); $attachment->setContentType("application/pdf"); $attachment->setContent(base64_encode(file_get_contents("/path/to/report.pdf"))); $message->setAttachments([$attachment]); ``` ## Send a message ```php theme={null} $response = $paubox->sendMessage($message); ``` The response is a `stdClass` object: | Property | Description | | - | - | | `sourceTrackingId` | Tracking ID for checking delivery status | | `data` | Raw response data | | `errors` | Array of error objects (`code`, `title`, `details`), if any | ```php theme={null} echo $response->sourceTrackingId; ``` ## Check delivery status ```php theme={null} $disposition = $paubox->getEmailDisposition($sourceTrackingId); ``` `$disposition->data->message->message_deliveries` is an array of per-recipient objects: ```php theme={null} foreach ($disposition->data->message->message_deliveries as $delivery) { echo $delivery->recipient . " → " . $delivery->status->deliveryStatus . PHP_EOL; } ``` Common `deliveryStatus` values: `delivered`, `delivered via secure portal`, `soft bounced`, `hard bounced`, `processing`. Opens are reported separately in `openedStatus`. ## Scheduled send Schedule a message for future delivery, check its status, reschedule, or cancel it. ### Schedule a message ```php theme={null} $scheduledAt = gmdate('Y-m-d\TH:i:s\Z', time() + 24 * 60 * 60); $response = $paubox->scheduleMessage($message, $scheduledAt); echo $response->sourceTrackingId; echo $response->scheduledAt; ``` `$scheduledAt` must be an ISO 8601 UTC datetime string in the future and within 30 days. ### Get scheduled message status ```php theme={null} $status = $paubox->getScheduledMessage($sourceTrackingId); echo $status->state; // "pending", "processing", "sent", "failed", "cancelled" echo $status->scheduledAt; ``` ### Reschedule a message ```php theme={null} $newTime = gmdate('Y-m-d\TH:i:s\Z', time() + 2 * 24 * 60 * 60); $response = $paubox->rescheduleMessage($sourceTrackingId, $newTime); echo $response->scheduledAt; ``` ### Cancel a scheduled message ```php theme={null} $response = $paubox->cancelScheduledMessage($sourceTrackingId); echo $response->state; // "cancelled" ``` In paubox-php 1.5.1 through 2.0.0, `cancelScheduledMessage` throws a `TypeError` from its HTTP library (`mb_strlen(): Argument #1 ($string) must be of type string, array given`) before the request is sent, so the message stays scheduled. ## Error handling `sendMessage` throws `\Exception` if the `Header` or `Content` is null, or if the API response is not JSON. `getEmailDisposition` throws if the response is not JSON. Neither method throws on HTTP error statuses: an API error is returned as a decoded object with an `errors` property, so check it: ```php theme={null} try { $response = $paubox->sendMessage($message); } catch (\Exception $e) { echo "Error: " . $e->getMessage() . PHP_EOL; exit(1); } if (!empty($response->errors)) { print_r($response->errors); } else { echo "Sent. Tracking ID: " . $response->sourceTrackingId . PHP_EOL; } ``` # PHP SDK forms client Source: https://docs.paubox.com/php-sdk/forms-client Retrieve Paubox Form schemas and submit form responses using the PHP SDK. `getForm` and `submitForm` do not require API credentials. Forms are identified by a UUID that you obtain from the Paubox dashboard. The form management methods require a scoped API key; see [Manage forms](#manage-forms). ## Instantiation ```php theme={null} $forms = new Paubox\PauboxForms(); ``` ## Get a form Retrieve a form's metadata, field schema, and rendered HTML/CSS: ```php theme={null} $form = $forms->getForm("your-form-uuid"); echo $form->title . PHP_EOL; echo $form->form_html . PHP_EOL; print_r($form->form_json); ``` The returned `stdClass` includes: | Property | Description | | - | - | | `title` | Display name of the form | | `form_json` | Parsed field schema | | `form_html` | Rendered HTML for embedding | | `form_css` | Associated stylesheet | | `active` | Whether the form is accepting submissions | | `submission_count` | Number of submissions received | `getForm` throws `Paubox\Forms\PauboxFormsException` if the form is not found or the response is invalid. ## Submit a form ```php theme={null} $submission = new Paubox\Forms\FormSubmission(); $submission->setFormData([ "first_name" => "Jane", "last_name" => "Smith", "email" => "jane@example.com", ]); $result = $forms->submitForm("your-form-uuid", $submission); // $result === true on success ``` `submitForm` returns `true` on a successful submission (HTTP 201) and throws `Paubox\Forms\PauboxFormsException` on failure. The message contains the operation and HTTP status; read the body with `getResponseBody()`. ### Submitting with file attachments The maximum total request size is 250 MB. ```php theme={null} $attachment = new Paubox\Forms\FormAttachment(); $attachment->setName("consent.pdf"); $attachment->setContent(base64_encode(file_get_contents("/path/to/consent.pdf"))); $submission = new Paubox\Forms\FormSubmission(); $submission->setFormData(["first_name" => "Jane"]); $submission->setAttachments([$attachment]); $result = $forms->submitForm("your-form-uuid", $submission); ``` The `FormAttachment` fields: | Field | Description | | - | - | | `name` | File name including extension | | `content` | Base64-encoded file content | ## Manage forms The management methods require a scoped API key with the `forms` scope, passed to the constructor or set as `PAUBOX_FORMS_API_KEY`. It can be the same key as `PAUBOX_API_KEY` if that key also has the `forms` scope. ```php theme={null} $forms = new Paubox\PauboxForms('YOUR_FORMS_API_KEY'); $result = $forms->listForms(['customer_id' => 12345]); foreach ($result->results as $form) { echo $form->title . PHP_EOL; } ``` Available methods: `getFormById`, `listForms`, `createForm`, `updateForm`, `archiveForm`, `unarchiveForm`, `copyForm`, `getFormStats`, `listSubmissions`, `getSubmissionsCsv`, `getSubmissionCsv`, and `getSubmissionPdf`. Calling one without a key throws `Paubox\Forms\PauboxFormsException`. ## Error handling API errors from Forms methods throw `Paubox\Forms\PauboxFormsException` (a network failure surfaces as Httpful's `ConnectionErrorException` instead), which provides `getStatusCode()`, `getUrl()`, and `getResponseBody()`: ```php theme={null} try { $form = $forms->getForm("your-form-uuid"); $result = $forms->submitForm("your-form-uuid", $submission); } catch (Paubox\Forms\PauboxFormsException $e) { echo "Error: " . $e->getMessage() . PHP_EOL; } ``` # Paubox PHP SDK Source: https://docs.paubox.com/php-sdk/index Send HIPAA compliant email and submit Paubox Forms from PHP applications using the official Paubox PHP SDK. The Paubox PHP SDK is the official PHP client library for the [Paubox Email API](/email-api) and [Paubox Forms](/forms). Install it with Composer and send encrypted, HIPAA compliant email with a few lines of PHP. ```bash theme={null} composer require paubox/paubox-php ``` ## What you can do * Send encrypted, HIPAA compliant email to one or more recipients * Add CC, BCC, attachments, and HTML or plain-text content * Track delivery status and engagement per recipient * Schedule, reschedule, and cancel future sends * Manage receiving domains and mailboxes, and read inbound email and attachments * Manage webhook endpoints for Email API and Forms events * Retrieve Paubox Form schemas and submit form responses with file attachments ## Requirements * PHP 8.1 or later * [Composer](https://getcomposer.org) * Dependencies installed automatically: `nategood/httpful` and `vlucas/phpdotenv` ## Get started > [card] [Quickstart](/php-sdk/quickstart) > > Install, configure your API key, and send your first email in minutes. > [card] [Authentication](/php-sdk/authentication) > > Set up your API key via a .env file. > [card] [Email client](/php-sdk/email-client) > > Full reference for sending email and checking delivery status. > [card] [Forms client](/php-sdk/forms-client) > > Retrieve form schemas and submit responses. ## Version note The current stable release (2.0.0) covers sending and scheduling email, receiving, webhooks, and the Forms API. A separate beta on the `sdk-generation/v2.0.0-beta` branch adds bulk sending and dynamic templates; it isn't part of the 2.0.0 release. This documentation covers 2.0.0. # PHP SDK quickstart Source: https://docs.paubox.com/php-sdk/quickstart Install the Paubox PHP SDK and send your first HIPAA compliant email in minutes. **1. Install the SDK** Add the SDK to your project with Composer: ```bash theme={null} composer require paubox/paubox-php ``` **2. Set your API key** Create a `.env` file in your project root: ```bash theme={null} PAUBOX_API_KEY=YOUR_API_KEY ``` The SDK reads `PAUBOX_API_KEY` from the environment but does not load `.env` itself. The next step loads it with `vlucas/phpdotenv`, which Composer installs with the SDK. To obtain your API key, see [Authentication](/php-sdk/authentication). **3. Send your first email** Create a file `send.php`: ```php theme={null} <?php require_once __DIR__ . '/vendor/autoload.php'; Dotenv\Dotenv::createUnsafeImmutable(__DIR__)->load(); $paubox = new Paubox\Paubox(); $message = new Paubox\Mail\Message(); $header = new Paubox\Mail\Header(); $header->setSubject("Your first Paubox email"); $header->setFrom("sender@yourdomain.com"); $content = new Paubox\Mail\Content(); $content->setPlainText("This message was sent with the Paubox PHP SDK."); $message->setHeader($header); $message->setContent($content); $message->setRecipients(["recipient@example.com"]); $response = $paubox->sendMessage($message); echo "Sent. Tracking ID: " . $response->sourceTrackingId . PHP_EOL; ``` Run it: ```bash theme={null} php send.php ``` ``` Sent. Tracking ID: abc123-def456-... ``` **4. Check delivery status** Use the tracking ID to check delivery: ```php theme={null} $disposition = $paubox->getEmailDisposition($response->sourceTrackingId); foreach ($disposition->data->message->message_deliveries as $delivery) { echo $delivery->recipient . " → " . $delivery->status->deliveryStatus . PHP_EOL; } ``` ``` recipient@example.com → delivered ``` ## Next steps * [Email client](/php-sdk/email-client): add HTML, attachments, CC/BCC, and handle errors * [Forms client](/php-sdk/forms-client): retrieve form schemas and submit responses # PHP SDK receiving client Source: https://docs.paubox.com/php-sdk/receiving-client Full reference for the Paubox PHP SDK receiving API: managing domains, mailboxes, and retrieving inbound email. Receiving endpoints are exposed through the `PauboxReceiving` class. Pass your Email API key to the constructor, or omit it to read `PAUBOX_API_KEY` from the environment. Methods return decoded JSON objects (`stdClass`). ```php theme={null} use Paubox\PauboxReceiving; $receiving = new PauboxReceiving('YOUR_API_KEY'); ``` ## Domains ### List domains ```php theme={null} $domains = $receiving->listReceivingDomains(); ``` ### Create a domain ```php theme={null} $domain = $receiving->createReceivingDomain('support'); echo $domain->data->domain; // support.inbound.paubox.email ``` Pass `null` to auto-generate a slug. ### Get a domain ```php theme={null} $domain = $receiving->getReceivingDomain(1); ``` ### Delete a domain ```php theme={null} $receiving->deleteReceivingDomain(1); ``` ## Mailboxes ### List mailboxes ```php theme={null} $mailboxes = $receiving->listMailboxes($domainId); ``` ### Create a mailbox ```php theme={null} $mailbox = $receiving->createMailbox($domainId, 'intake', 'SecurePass123!'); echo $mailbox->data->email_address; ``` Pass a fourth argument for `quotaBytes`. ### Get a mailbox ```php theme={null} $mailbox = $receiving->getMailbox($domainId, $mailboxId); ``` ### Delete a mailbox ```php theme={null} $receiving->deleteMailbox($domainId, $mailboxId); ``` ## Emails ### List received emails ```php theme={null} $emails = $receiving->listReceivedEmails(['limit' => 10]); ``` The array also accepts `after` and `before` cursors for pagination, and `search`. ### Get a received email ```php theme={null} $email = $receiving->getReceivedEmail($emailId); echo $email->data->text_body; ``` ### Download an attachment ```php theme={null} $attachmentId = $email->data->attachments[0]->id; $data = $receiving->downloadAttachment($emailId, $attachmentId); file_put_contents('report.pdf', $data); ``` `downloadAttachment` returns the raw file bytes as a string. ## Error handling A non-2xx response throws `Paubox\Receiving\PauboxReceivingException`, which provides `getStatusCode()`, `getUrl()`, and `getResponseBody()`. It is also thrown when no API key is set. # PHP SDK webhook client Source: https://docs.paubox.com/php-sdk/webhook-client Create, list, get, update, and delete Paubox webhook endpoints with the PHP SDK to receive Email API and Forms events. > [!NOTE] > > The methods on this page require SDK 2.0.0 or later, where `Paubox\PauboxWebhooks` uses the Paubox webhooks service and a scoped API key. `Paubox\PauboxWebhooks` manages webhook endpoints through the Paubox webhooks service at `https://api.paubox.com/v1/webhooks`. It sends a scoped API key as `Authorization: Bearer YOUR_API_KEY`. The key's scopes decide which events it can subscribe to. ## Create the client ```php theme={null} use Paubox\PauboxWebhooks; $webhooks = new PauboxWebhooks('YOUR_API_KEY'); ``` When the key is omitted, the client reads the `PAUBOX_WEBHOOKS_API_KEY` environment variable. Pass a base URL as the second argument or set `PAUBOX_WEBHOOKS_BASE_URL` to override it. Every method throws `Paubox\Webhooks\PauboxWebhooksException` before sending a request if no key is set. ## Events | Event | Required scope | Fires when | | - | - | - | | `api_mail_log_delivered` | `email_api` | An Email API message is delivered | | `api_mail_log_opened` | `email_api` | A delivered message is opened | | `api_mail_log_temporary_failure` | `email_api` | Delivery fails temporarily | | `api_mail_log_permanent_failure` | `email_api` | Delivery fails permanently | | `email.inbound.received` | `email_api`, with no sender-domain limit | Inbound mail is received | | `forms.submission.created` | `forms` | A form submission is received | The SDK doesn't check event names. The API returns 422 for an unknown event and 403 for an event the key isn't scoped for. Email API keys created in the Paubox Dashboard are limited to a sender domain, so subscribe to inbound mail in the Paubox Dashboard under [Settings > Webhooks](https://next.paubox.com/settings/webhooks). For payloads and signature verification, see [Webhooks](/email-api/webhooks). ## List webhook endpoints ```php theme={null} $result = $webhooks->listWebhookEndpoints(['page' => 1, 'items' => 50]); foreach ($result->data as $endpoint) { echo $endpoint->id . ' ' . $endpoint->target_url . ' ' . $endpoint->status . "\n"; } echo $result->page_info->count . "\n"; ``` The argument is optional. Responses are decoded into objects. `page_info->count` is the total number of endpoints, not the length of this page. Endpoints carrying an event the key isn't scoped for are left out. ## Create a webhook endpoint ```php theme={null} $endpoint = $webhooks->createWebhookEndpoint([ 'target_url' => 'https://example.com/webhooks/paubox', 'events' => ['api_mail_log_delivered', 'api_mail_log_opened'], ]); echo $endpoint->id . "\n"; echo $endpoint->signing_secret . "\n"; ``` `target_url` must be an `https` URL that doesn't point at a private or internal address. The array is sent to the API as given, so pass only `target_url` and `events`. Each endpoint has `id` (a UUID), `target_url`, `status` (`active` or `disabled`), `events`, `created_at`, and `updated_at`. `signing_secret` is returned only by this call; store it when you create the endpoint. To replace a lost secret, delete the endpoint and create a new one. ## Get a webhook endpoint ```php theme={null} $endpoint = $webhooks->getWebhookEndpoint('2ec66c21-bf48-48eb-8d28-f80b2d6b77c7'); ``` ## Update a webhook endpoint ```php theme={null} $endpoint = $webhooks->updateWebhookEndpoint('2ec66c21-bf48-48eb-8d28-f80b2d6b77c7', [ 'status' => 'disabled', ]); ``` Pass any of `target_url`, `status` (`active` or `disabled`), and `events`. `events` replaces the endpoint's event list. ## Delete a webhook endpoint ```php theme={null} $webhooks->deleteWebhookEndpoint('2ec66c21-bf48-48eb-8d28-f80b2d6b77c7'); ``` Returns `true`. ## Error handling ```php theme={null} use Paubox\Webhooks\PauboxWebhooksException; try { $webhooks->createWebhookEndpoint([ 'target_url' => 'https://example.com/webhooks/paubox', 'events' => ['api_mail_log_delivered'], ]); } catch (PauboxWebhooksException $e) { echo $e->getStatusCode() . ' ' . $e->getMessage() . "\n"; } ``` Webhook methods throw `Paubox\Webhooks\PauboxWebhooksException` on a non-2xx response. It provides `getStatusCode()`, `getUrl()`, and `getResponseBody()`, and its message includes the API's error text. Creating a second endpoint for the same `target_url` returns 422, and an ID that isn't on your account returns 404. An ID that isn't a UUID throws before any request is sent. # Python SDK authentication Source: https://docs.paubox.com/python-sdk/authentication Configure Paubox API credentials for the Python SDK with environment variables or constructor parameters, plus Forms client setup and key security notes. ## Obtain your credentials The Email API client requires one value: * **API key**: a secret token that authenticates your requests Your API key is available in the [Paubox dashboard](https://next.paubox.com) under **API Credentials**. ## Environment variables (recommended) Set the key in your shell or a `.env` file loaded by your application: ```bash theme={null} PAUBOX_API_KEY=YOUR_API_KEY ``` The SDK reads `PAUBOX_API_KEY` when the `paubox` package is first imported, so set it (or load your `.env` file) before that import. No constructor arguments are needed: ```python theme={null} from paubox import PauboxApiClient client = PauboxApiClient() ``` ## Constructor parameters Pass credentials directly if you prefer not to use environment variables: ```python theme={null} client = PauboxApiClient(api_key='YOUR_API_KEY') ``` The client sends requests to `https://api.paubox.com/v1/email` by default. Leave `PAUBOX_HOST` and `host` unset unless you need to override that base URL; an override must include the `/email` path. The SDK sets the `Authorization` header automatically on every request: ``` Authorization: Token token=YOUR_API_KEY ``` ## Forms client `get_form` and `submit_form` on `PauboxFormsClient` require no credentials: ```python theme={null} from paubox import PauboxFormsClient forms_client = PauboxFormsClient() ``` The form management methods (for example `list_forms`, `create_form`, and `list_submissions`) require a scoped API key with the `forms` scope, sent as `Authorization: Bearer`. It can be the same key as `PAUBOX_API_KEY` if that key also has the `forms` scope: ```python theme={null} forms_client = PauboxFormsClient(api_key='YOUR_FORMS_API_KEY') ``` ## Security notes * Never hard-code credentials in source files. * The SDK does not log API keys or request bodies. # Python SDK email client Source: https://docs.paubox.com/python-sdk/email-client Full reference for the Paubox Python SDK email client: composing messages, sending email, tracking delivery, and error handling. ## Instantiation ```python theme={null} from paubox import PauboxApiClient # Read credentials from environment variables client = PauboxApiClient() # Or pass credentials directly client = PauboxApiClient(api_key='YOUR_API_KEY') ``` See [Authentication](/python-sdk/authentication) for both approaches. ## Composing a message Use the `Mail` helper to compose messages. It handles formatting and automatically base64-encodes HTML content before sending. ```python theme={null} from paubox.helpers.mail import Mail mail = Mail( from_ = 'sender@yourdomain.com', # required subject = 'Your results are ready', # required recipients = ['alice@example.com'], # required; list of email strings content = { # required; at least one key 'text/plain': 'Plain text body.', 'text/html': '<p>HTML body.</p>' # auto base64-encoded }, optional_headers = { # optional 'reply_to': 'support@yourdomain.com', 'cc': ['manager@example.com'], 'bcc': ['audit@example.com'], # list of email strings 'allowNonTLS': False, 'forceSecureNotification': False, 'attachments': [attachment] } ) ``` Call `mail.get()` to get the formatted dict ready for the API. ### Attachments ```python theme={null} import base64 with open('report.pdf', 'rb') as f: encoded = base64.b64encode(f.read()).decode('utf-8') attachment = { 'fileName': 'report.pdf', 'contentType': 'application/pdf', 'content': encoded } ``` Pass attachments via the `optional_headers` dict: ```python theme={null} optional_headers = { 'attachments': [attachment] } ``` ## Send a message ```python theme={null} response = client.send(mail.get()) print('Status:', response.status_code) print('Tracking ID:', response.to_dict.get('sourceTrackingId')) ``` ## Check delivery status ```python theme={null} tracking_id = response.to_dict['sourceTrackingId'] disposition = client.get(tracking_id) deliveries = disposition.to_dict['data']['message']['message_deliveries'] for d in deliveries: print(d['recipient'], '→', d['status']['deliveryStatus']) ``` Common `deliveryStatus` values: `delivered`, `delivered via secure portal`, `soft bounced`, `hard bounced`, `processing`. Opens are reported separately in `openedStatus`. ## Scheduled send Schedule a message for future delivery, check its status, reschedule, or cancel it. ### Schedule a message ```python theme={null} from datetime import datetime, timedelta, timezone scheduled_at = (datetime.now(timezone.utc) + timedelta(days=1)).isoformat() response = client.schedule(mail.get(), scheduled_at) print('Tracking ID:', response.to_dict.get('sourceTrackingId')) print('Scheduled for:', response.to_dict.get('scheduledAt')) ``` `scheduled_at` must be an ISO 8601 UTC datetime string in the future and within 30 days. ### Get scheduled message status ```python theme={null} status = client.get_scheduled(source_tracking_id) data = status.to_dict print('State:', data.get('state')) # "pending", "processing", "sent", "failed", "cancelled" print('Scheduled for:', data.get('scheduledAt')) ``` ### Reschedule a message ```python theme={null} new_time = (datetime.now(timezone.utc) + timedelta(days=2)).isoformat() response = client.reschedule(source_tracking_id, new_time) print('New time:', response.to_dict.get('scheduledAt')) ``` ### Cancel a scheduled message ```python theme={null} response = client.cancel_scheduled(source_tracking_id) print('State:', response.to_dict.get('state')) # "cancelled" ``` ## The Response object Every `PauboxApiClient` method returns a `Response` object: | Property | Description | | - | - | | `.status_code` | HTTP status code | | `.headers` | Response headers dict | | `.text` | Raw response body as a string | | `.content` | Raw response body as bytes | | `.to_dict` | JSON-parsed response body, or `None` if the body is empty; raises `json.JSONDecodeError` if the body isn't JSON | ## Error handling All client methods raise `requests.exceptions.HTTPError` on non-2xx responses. Before raising, the SDK prints the error response body to standard output. Wrap calls in a try/except block: ```python theme={null} import requests try: response = client.send(mail.get()) except requests.exceptions.HTTPError as e: print('API error:', e.response.status_code, e.response.text) ``` # Python SDK forms client Source: https://docs.paubox.com/python-sdk/forms-client Retrieve Paubox Form schemas and submit form responses using the Python SDK. `get_form` and `submit_form` do not require API credentials. Forms are identified by a UUID that you obtain from the Paubox dashboard. The form management methods require a scoped API key; see [Manage forms](#manage-forms). ## Instantiation ```python theme={null} from paubox import PauboxFormsClient client = PauboxFormsClient() ``` ## Get a form Retrieve a form's metadata, field schema, and rendered HTML/CSS: ```python theme={null} response = client.get_form('your-form-uuid') form = response.to_dict print('Title:', form['title']) print('HTML:', form['form_html']) ``` Key fields in the response: | Field | Description | | - | - | | `title` | Display name of the form | | `form_json` | Parsed field schema | | `form_html` | Rendered HTML for embedding | | `form_css` | Associated stylesheet | | `active` | Whether the form is accepting submissions | | `submission_count` | Number of submissions received | ## Submit a form ```python theme={null} form_data = { 'first_name': 'Jane', 'last_name': 'Smith', 'email': 'jane@example.com' } response = client.submit_form('your-form-uuid', form_data) print('Status:', response.status_code) # 201 on success ``` `submit_form` raises `ValueError` if `form_data` is empty or `None`. ### Submitting with file attachments The maximum total request size is 250 MB. ```python theme={null} import base64 with open('consent.pdf', 'rb') as f: encoded = base64.b64encode(f.read()).decode('utf-8') attachments = [ {'name': 'consent.pdf', 'content': encoded} ] response = client.submit_form('your-form-uuid', form_data, attachments) ``` Each attachment is a dict with two keys: | Key | Description | | - | - | | `name` | File name including extension | | `content` | Base64-encoded file content | ## Manage forms The management methods require a scoped API key with the `forms` scope, passed as `api_key`. It can be the same key as `PAUBOX_API_KEY` if that key also has the `forms` scope. ```python theme={null} client = PauboxFormsClient(api_key='YOUR_FORMS_API_KEY') response = client.list_forms() print(response.to_dict) ``` Available methods: `get_form_by_id`, `list_forms`, `create_form`, `update_form`, `archive_form`, `unarchive_form`, `copy_form`, `get_form_stats`, `list_submissions`, `export_submissions_csv`, and `export_submission_pdf`. Calling one without a key raises `ValueError`. ## Error handling ```python theme={null} import requests try: response = client.get_form('your-form-uuid') response = client.submit_form('your-form-uuid', form_data) except ValueError as e: print('Invalid input:', e) except requests.exceptions.HTTPError as e: print('API error:', e.response.status_code, e.response.text) ``` # Paubox Python SDK Source: https://docs.paubox.com/python-sdk/index Send HIPAA compliant email and submit Paubox Forms from Python 3 applications using the official Paubox Python SDK. The Paubox Python SDK is the official Python 3 client library for the [Paubox Email API](/email-api) and [Paubox Forms](/forms). It provides a clean interface for sending encrypted email, tracking delivery, and submitting form responses with a single external dependency (`requests`). ```bash theme={null} pip3 install "git+https://github.com/Paubox/paubox-python3@v2.0.0" ``` This documentation covers v2.0.0. The `paubox-python3` package on PyPI is an old release (1.0.1) that predates these docs; install from GitHub. ## What you can do * Send encrypted, HIPAA compliant email to one or more recipients * Add CC, BCC, attachments, and HTML or plain-text content * Track delivery status and engagement per recipient * Schedule, reschedule, and cancel future sends * Manage receiving domains and mailboxes, and read inbound email and attachments * Manage webhook endpoints for Email API and Forms events * Retrieve Paubox Form schemas and submit form responses with file attachments ## Requirements * Python 3 * `requests` (installed automatically) ## Get started > [card] [Quickstart](/python-sdk/quickstart) > > Install, configure credentials, and send your first email in minutes. > [card] [Authentication](/python-sdk/authentication) > > Set up your API key via environment variables. > [card] [Email client](/python-sdk/email-client) > > Full reference for composing and sending email, and checking delivery status. > [card] [Forms client](/python-sdk/forms-client) > > Retrieve form schemas and submit responses. ## Version note The current stable release (2.0.0) covers sending and scheduling email, receiving, webhooks, and the Forms API. A separate beta on the `sdk-generation/v2.0.0-beta` branch adds bulk sending and dynamic templates; it isn't part of the 2.0.0 release. This documentation covers 2.0.0. # Python SDK quickstart Source: https://docs.paubox.com/python-sdk/quickstart Install the Paubox Python SDK and send your first HIPAA compliant email in minutes. **1. Install the SDK** ```bash theme={null} pip3 install "git+https://github.com/Paubox/paubox-python3@v2.0.0" ``` The `paubox-python3` package on PyPI is an old release (1.0.1) that predates these docs; install from GitHub. **2. Set your credentials** Export your API key as an environment variable: ```bash theme={null} export PAUBOX_API_KEY="YOUR_API_KEY" ``` To obtain your API key, see [Authentication](/python-sdk/authentication). **3. Send your first email** Create `send.py`: ```python theme={null} from paubox import PauboxApiClient from paubox.helpers.mail import Mail client = PauboxApiClient() mail = Mail( from_ = 'sender@yourdomain.com', subject = 'Your first Paubox email', recipients = ['recipient@example.com'], content = {'text/plain': 'This message was sent with the Paubox Python SDK.'} ) response = client.send(mail.get()) print('Status:', response.status_code) print('Response:', response.to_dict) ``` Run it: ```bash theme={null} python3 send.py ``` The response dict contains `sourceTrackingId`. **4. Check delivery status** ```python theme={null} tracking_id = response.to_dict['sourceTrackingId'] disposition = client.get(tracking_id) print(disposition.to_dict) ``` The response includes `message_deliveries` with per-recipient status. ## Next steps * [Email client](/python-sdk/email-client): add HTML, attachments, CC/BCC, and handle errors * [Forms client](/python-sdk/forms-client): retrieve form schemas and submit responses # Python SDK receiving client Source: https://docs.paubox.com/python-sdk/receiving-client Full reference for the Paubox Python SDK receiving API: managing domains, mailboxes, and retrieving inbound email. The receiving methods are on the same `PauboxApiClient` you use to send email. ```python theme={null} from paubox.paubox import PauboxApiClient client = PauboxApiClient(api_key='YOUR_API_KEY') ``` ## Domains ### List domains ```python theme={null} resp = client.list_receiving_domains() for domain in resp.to_dict['data']: print(domain['domain']) ``` ### Create a domain ```python theme={null} resp = client.create_receiving_domain(slug='support') print(resp.to_dict['data']['domain']) # support.inbound.paubox.email ``` Omit `slug` to auto-generate one. ### Get a domain ```python theme={null} resp = client.get_receiving_domain(1) ``` ### Delete a domain ```python theme={null} client.delete_receiving_domain(1) ``` ## Mailboxes ### List mailboxes ```python theme={null} resp = client.list_receiving_mailboxes(domain_id) ``` ### Create a mailbox ```python theme={null} resp = client.create_receiving_mailbox(domain_id, 'intake', 'SecurePass123!') print(resp.to_dict['data']['email_address']) ``` Pass `quota_bytes=` to set a storage quota. ### Get a mailbox ```python theme={null} resp = client.get_receiving_mailbox(domain_id, mailbox_id) ``` ### Delete a mailbox ```python theme={null} client.delete_receiving_mailbox(domain_id, mailbox_id) ``` ## Emails ### List received emails ```python theme={null} resp = client.list_received_emails(limit=10) for email in resp.to_dict['data']: print(f"{email['email_id']}: {email['subject']}") # Cursor pagination; search, sort, and ascending are also accepted next_page = client.list_received_emails(after=resp.to_dict['data'][-1]['email_id']) ``` ### Get a received email ```python theme={null} resp = client.get_received_email(email_id) print(resp.to_dict['data']['text_body']) ``` ### List attachments ```python theme={null} resp = client.list_received_email_attachments(email_id) ``` ### Download an attachment ```python theme={null} attachment_id = client.get_received_email(email_id).to_dict['data']['attachments'][0]['id'] resp = client.get_received_email_attachment(email_id, attachment_id) with open('report.pdf', 'wb') as f: f.write(resp.content) ``` Each method returns a [`Response`](/python-sdk/email-client#the-response-object) and raises `requests.exceptions.HTTPError` on a non-2xx response. # Python SDK webhook client Source: https://docs.paubox.com/python-sdk/webhook-client Create, list, get, update, and delete Paubox webhook endpoints with the Python SDK to receive Email API and Forms events. > [!NOTE] > > Webhook endpoint methods require SDK 2.0.0 or later. They are on `PauboxWebhooksClient`, not on the `PauboxApiClient` you use to send email. `PauboxWebhooksClient` manages webhook endpoints through the Paubox webhooks service at `https://api.paubox.com/v1/webhooks`. It sends a scoped API key as `Authorization: Bearer YOUR_API_KEY`. The key's scopes decide which events it can subscribe to. ## Create the client ```python theme={null} from paubox import PauboxWebhooksClient webhooks = PauboxWebhooksClient(api_key="YOUR_API_KEY") ``` The client doesn't read an environment variable; pass `api_key` explicitly, as a keyword argument. The first positional argument is `base_url`, so `PauboxWebhooksClient("YOUR_API_KEY")` treats the key as the base URL. Pass `base_url` to override the base URL. Every method raises `ValueError` before sending a request if no key is set. ## Events | Event | Required scope | Fires when | | - | - | - | | `api_mail_log_delivered` | `email_api` | An Email API message is delivered | | `api_mail_log_opened` | `email_api` | A delivered message is opened | | `api_mail_log_temporary_failure` | `email_api` | Delivery fails temporarily | | `api_mail_log_permanent_failure` | `email_api` | Delivery fails permanently | | `email.inbound.received` | `email_api`, with no sender-domain limit | Inbound mail is received | | `forms.submission.created` | `forms` | A form submission is received | The SDK doesn't check event names. The API returns 422 for an unknown event and 403 for an event the key isn't scoped for. Email API keys created in the Paubox Dashboard are limited to a sender domain, so subscribe to inbound mail in the Paubox Dashboard under [Settings > Webhooks](https://next.paubox.com/settings/webhooks). For payloads and signature verification, see [Webhooks](/email-api/webhooks). ## List webhook endpoints ```python theme={null} response = webhooks.list_webhook_endpoints(page=1, items=50) body = response.to_dict for endpoint in body["data"]: print(endpoint["id"], endpoint["target_url"], endpoint["status"]) print(body["page_info"]["count"]) ``` Every method returns a `Response`; read the parsed JSON from `to_dict`. `page` and `items` are optional. `page_info["count"]` is the total number of endpoints, not the length of this page. Endpoints carrying an event the key isn't scoped for are left out. ## Create a webhook endpoint ```python theme={null} response = webhooks.create_webhook_endpoint( target_url="https://example.com/webhooks/paubox", events=["api_mail_log_delivered", "api_mail_log_opened"], ) endpoint = response.to_dict["data"] print(endpoint["id"]) print(endpoint["signing_secret"]) ``` `target_url` must be an `https` URL that doesn't point at a private or internal address. Each endpoint has `id` (a UUID), `target_url`, `status` (`active` or `disabled`), `events`, `created_at`, and `updated_at`. `signing_secret` is returned only by this call; store it when you create the endpoint. To replace a lost secret, delete the endpoint and create a new one. ## Get a webhook endpoint ```python theme={null} endpoint = webhooks.get_webhook_endpoint("2ec66c21-bf48-48eb-8d28-f80b2d6b77c7").to_dict["data"] ``` ## Update a webhook endpoint ```python theme={null} endpoint = webhooks.update_webhook_endpoint( "2ec66c21-bf48-48eb-8d28-f80b2d6b77c7", status="disabled", ).to_dict["data"] ``` Pass any of `target_url`, `status` (`"active"` or `"disabled"`), and `events`. Only the arguments you pass are sent. `events` replaces the endpoint's event list. ## Delete a webhook endpoint ```python theme={null} response = webhooks.delete_webhook_endpoint("2ec66c21-bf48-48eb-8d28-f80b2d6b77c7") print(response.status_code) ``` The API responds with `204 No Content`, so `to_dict` is `None`. ## Error handling ```python theme={null} import requests try: webhooks.create_webhook_endpoint( target_url="https://example.com/webhooks/paubox", events=["api_mail_log_delivered"], ) except requests.exceptions.HTTPError as err: print(err.response.status_code, err) ``` A non-2xx response raises `requests.exceptions.HTTPError` whose message is the API's error text. Creating a second endpoint for the same `target_url` returns 422, and an ID that isn't on your account returns 404. An ID that isn't a UUID raises `ValueError` before any request is sent. # Rails SDK authentication Source: https://docs.paubox.com/rails-sdk/authentication Configure Paubox API credentials for the Rails SDK in an initializer backed by environment variables, plus Forms client setup and key security notes. ## Obtain your API key The Email API requires one credential: * **API key**: a secret token that authenticates your requests It is available in the [Paubox dashboard](https://next.paubox.com) under **API Credentials**. ## Configure the initializer Create `config/initializers/paubox.rb`: ```ruby theme={null} Paubox.configure do |config| config.api_key = ENV['PAUBOX_API_KEY'] end ``` The gem's Railtie registers the `:paubox` delivery method. Each delivery reads `Paubox.configuration`, so no per-request setup is needed. ## Set environment variables Add your API key to your environment (e.g. via a `.env` file with `dotenv-rails`, Rails credentials, or your deployment platform's secret management): ```bash theme={null} PAUBOX_API_KEY=YOUR_API_KEY ``` ## Forms client `get_form` and `submit_form` on `PauboxRails::Forms::Client` require no credentials. Form submissions are associated with the form ID, not an API key. ```ruby theme={null} client = PauboxRails::Forms.client ``` The form management methods (for example `list_forms`, `create_form`, and `list_submissions`) require a scoped API key with the `forms` scope, sent as `Authorization: Bearer`. It can be the same key as the Email API key if that key also has the `forms` scope. Pass it as `api_key:` or set `PAUBOX_FORMS_API_KEY`: ```ruby theme={null} client = PauboxRails::Forms.client(api_key: ENV['PAUBOX_FORMS_API_KEY']) ``` ## Security notes * Never hard-code credentials in initializer files; always read from environment variables or encrypted credentials. * The gem does not log API keys or request bodies. # Email delivery Source: https://docs.paubox.com/rails-sdk/email-delivery Send HIPAA compliant email through ActionMailer using the Paubox Rails gem. ## How it works `paubox_rails` registers `:paubox` as an ActionMailer delivery method. Your mailer classes are standard Rails mailers; the gem intercepts delivery and routes each message through the Paubox Email API, ensuring every email is encrypted and HIPAA compliant. ## Set the delivery method **Globally** (all environments): ```ruby theme={null} # config/application.rb config.action_mailer.delivery_method = :paubox ``` **Per environment** (recommended for production only): ```ruby theme={null} # config/environments/production.rb config.action_mailer.delivery_method = :paubox ``` Leave development and test environments using `:letter_opener`, `:test`, or another local delivery method. ## Create a mailer Mailers work exactly as documented in the [Rails ActionMailer guide](https://guides.rubyonrails.org/action_mailer_basics.html): ```ruby theme={null} class PatientMailer < ApplicationMailer def appointment_reminder @patient = params[:patient] @appointment = params[:appointment] mail( to: @patient.email, from: "appointments@yourclinic.com", subject: "Appointment reminder" ) end end ``` Templates live in `app/views/patient_mailer/` as usual (`appointment_reminder.html.erb`, `appointment_reminder.text.erb`). ## Deliver email ```ruby theme={null} # Synchronous delivery PatientMailer.with(patient: patient, appointment: appt).appointment_reminder.deliver_now # Asynchronous delivery (via Active Job) PatientMailer.with(patient: patient, appointment: appt).appointment_reminder.deliver_later ``` ## Per-message options To allow delivery without TLS for a specific message, set `allow_non_tls` on the message that `mail()` returns. Passing it in `delivery_method_options` has no effect. ```ruby theme={null} mail( to: @patient.email, subject: "Lab results" ).tap { |m| m.allow_non_tls = true } ``` `force_secure_notification` is not applied to messages sent through ActionMailer. To use it, send a `Paubox::Message` with `Paubox::Client#send_mail`; see the [Ruby SDK email client](/ruby-sdk/email-client). ## Attachments Attach files using standard ActionMailer attachment helpers: ```ruby theme={null} def report_email attachments["results.pdf"] = File.read(Rails.root.join("tmp/results.pdf")) mail( to: params[:patient].email, subject: "Your lab results" ) end ``` ## Scheduled send Schedule messages for future delivery using `Paubox::Client` directly. The scheduled send methods are provided by the [Paubox Ruby gem](/ruby-sdk/email-client#scheduled-send), which `paubox_rails` depends on. ```ruby theme={null} client = Paubox::Client.new message = Paubox::Message.new( from: 'sender@yourdomain.com', to: ['recipient@example.com'], subject: 'Scheduled message', text_content: 'This will be delivered later.' ) # Schedule a message response = client.schedule_mail(message, 1.day.from_now.utc.iso8601) puts response['sourceTrackingId'] # Check status status = client.get_scheduled(response['sourceTrackingId']) puts status['state'] # "pending", "processing", "sent", "failed", "cancelled" # Reschedule client.reschedule(response['sourceTrackingId'], 2.days.from_now.utc.iso8601) # Cancel client.cancel_scheduled(response['sourceTrackingId']) ``` `scheduled_at` must be an ISO 8601 UTC datetime string in the future and within 30 days. ## Tracking IDs After a synchronous send, the Paubox tracking ID is on the message: ```ruby theme={null} delivery = PatientMailer.with(patient: patient, appointment: appt).appointment_reminder delivery.deliver_now delivery.source_tracking_id ``` Look up its delivery status with `Paubox::Client.new.email_disposition(delivery.source_tracking_id)`. With `deliver_later`, the ID is set on the message inside the job, so the caller doesn't see it. # Rails SDK forms client Source: https://docs.paubox.com/rails-sdk/forms-client Retrieve Paubox Form schemas and submit form responses using the Rails SDK. `get_form` and `submit_form` do not require API credentials. Forms are identified by a UUID that you obtain from the Paubox dashboard. The form management methods require a scoped API key; see [Manage forms](#manage-forms). ## Create a client ```ruby theme={null} client = PauboxRails::Forms.client ``` `PauboxRails::Forms.client` returns a new `PauboxRails::Forms::Client` instance. ## Get a form Retrieve a form's metadata, field schema, and rendered HTML/CSS: ```ruby theme={null} form = client.get_form("your-form-uuid") puts form["title"] puts form["form_html"] puts form["form_json"].inspect ``` The return value is a Hash with the following keys: | Key | Description | | - | - | | `"title"` | Display name of the form | | `"form_json"` | Parsed field schema | | `"form_html"` | Rendered HTML for embedding | | `"form_css"` | Associated stylesheet | | `"active"` | Whether the form is accepting submissions | | `"submission_count"` | Number of submissions received | `get_form` raises `PauboxRails::Forms::NotFoundError` if no form exists for the ID (HTTP 404). ## Submit a form ```ruby theme={null} result = client.submit_form( "your-form-uuid", form_data: { "first_name" => "Jane", "last_name" => "Smith", "email" => "jane@example.com" } ) # result => true ``` `submit_form` returns `true` on a successful submission (HTTP 201). ### Submitting with file attachments The maximum total request size is 250 MB. ```ruby theme={null} require "base64" encoded = Base64.strict_encode64(File.read(Rails.root.join("tmp/consent.pdf"))) result = client.submit_form( "your-form-uuid", form_data: { "first_name" => "Jane" }, attachments: [ { name: "consent.pdf", content: encoded } ] ) ``` Each attachment is a Hash with two keys: | Key | Description | | - | - | | `:name` | File name including extension | | `:content` | Base64-encoded file content | ## Manage forms The management methods require a scoped API key with the `forms` scope, passed as `api_key:` or set as `PAUBOX_FORMS_API_KEY`. It can be the same key as the Email API key if that key also has the `forms` scope. ```ruby theme={null} client = PauboxRails::Forms.client(api_key: ENV['PAUBOX_FORMS_API_KEY']) result = client.list_forms(customer_id: 12345) ``` Available methods: `get_form_details`, `list_forms` (requires `customer_id:`), `create_form`, `update_form`, `archive_form`, `unarchive_form`, `copy_form`, `form_stats`, `list_submissions`, `submissions_csv`, and `submission_pdf`. Calling one without a key raises `PauboxRails::Forms::MissingApiKeyError`. ## Error handling All Forms errors inherit from `PauboxRails::Forms::Error`: `NotFoundError` (HTTP 404), `BadRequestError` (HTTP 400 or 422), `UnauthorizedError` (HTTP 401), `ForbiddenError` (HTTP 403), and `MissingApiKeyError`. An empty ID, or a non-UUID form or submission ID in the URL of a management method (every method except `copy_form`), raises `ArgumentError` before a request is made. ```ruby theme={null} begin form = client.get_form("your-form-uuid") result = client.submit_form("your-form-uuid", form_data: data) rescue PauboxRails::Forms::NotFoundError # Form UUID not found (HTTP 404) rescue PauboxRails::Forms::BadRequestError # Malformed request (HTTP 400 or 422) rescue PauboxRails::Forms::Error => e # Any other Forms API error Rails.logger.error("Forms error: #{e.message}") end ``` # Paubox Rails SDK Source: https://docs.paubox.com/rails-sdk/index Send HIPAA compliant email from Rails applications using ActionMailer and the official Paubox Rails gem. The Paubox Rails SDK (`paubox_rails`) integrates the [Paubox Email API](/email-api) directly into Rails as an ActionMailer delivery method. Your mailer classes work exactly as they do today; just point ActionMailer at Paubox and every email you send becomes encrypted and HIPAA compliant. The gem also includes a lightweight client for the [Paubox Forms API](/forms). ```ruby theme={null} # Gemfile gem 'paubox_rails' ``` ## What you can do * Send encrypted, HIPAA compliant email through standard Rails mailers and ActionMailer * Use HTML and plain-text templates, CC and BCC, reply-to, and attachments. Other headers are not sent to Paubox. * Deliver synchronously with `deliver_now` or asynchronously with `deliver_later` * Schedule sends, manage receiving domains and mailboxes, and read inbound email through `Paubox::Client` from the `paubox` gem * Manage webhook endpoints with `PauboxRails::Webhooks` * Retrieve Paubox Form schemas and submit form responses with file attachments ## Requirements * ActionMailer 4.0 or later. The samples use parameterized mailers (`with` and `params`), which need Rails 5.1 or later. * Ruby 2.5 or later * Dependencies installed automatically: `actionmailer` and the `paubox` gem (`~> 1.0`) The scheduling and receiving samples need `paubox` 1.3.1 or later. Run `bundle update paubox` if your lockfile has an older 1.x version. The webhook samples need `paubox_rails` 1.2.0 or later. ## Get started > [card] [Quickstart](/rails-sdk/quickstart) > > Add the gem, configure credentials, and send your first email in minutes. > [card] [Authentication](/rails-sdk/authentication) > > Configure your API key via a Rails initializer. > [card] [Email delivery](/rails-sdk/email-delivery) > > Full guide to sending email through ActionMailer with Paubox. > [card] [Forms client](/rails-sdk/forms-client) > > Retrieve form schemas and submit responses. # Rails SDK quickstart Source: https://docs.paubox.com/rails-sdk/quickstart Add the Paubox Rails gem, configure credentials, and send your first HIPAA compliant email in minutes. **1. Add the gem** Add `paubox_rails` to your Gemfile: ```ruby theme={null} gem 'paubox_rails' ``` Then install: ```bash theme={null} bundle install ``` **2. Configure credentials** Create `config/initializers/paubox.rb`: ```ruby theme={null} Paubox.configure do |config| config.api_key = ENV['PAUBOX_API_KEY'] end ``` To obtain credentials, see [Authentication](/rails-sdk/authentication). **3. Set the delivery method** In `config/application.rb` (or an environment-specific file): ```ruby theme={null} config.action_mailer.delivery_method = :paubox ``` **4. Create a mailer and send** Generate a mailer if you don't have one: ```bash theme={null} rails generate mailer UserMailer ``` Define an action in `app/mailers/user_mailer.rb`: ```ruby theme={null} class UserMailer < ApplicationMailer def welcome_email @user = params[:user] mail( to: @user.email, from: "noreply@yourdomain.com", subject: "Welcome to the portal" ) end end ``` Add a template at `app/views/user_mailer/welcome_email.html.erb`: ```erb theme={null} <p>Hello <%= @user.name %>,</p> <p>Your account is ready. Log in at any time.</p> ``` Deliver it: ```ruby theme={null} UserMailer.with(user: current_user).welcome_email.deliver_now ``` The email is sent encrypted via Paubox. ## Next steps * [Email delivery](/rails-sdk/email-delivery): per-message options, attachments, async delivery * [Forms client](/rails-sdk/forms-client): retrieve form schemas and submit responses # Rails SDK receiving client Source: https://docs.paubox.com/rails-sdk/receiving-client Full reference for the Paubox Rails SDK receiving API: managing domains, mailboxes, and retrieving inbound email. The receiving methods are on `Paubox::Client` from the `paubox` gem, which `paubox_rails` installs and loads. With the initializer from [Authentication](/rails-sdk/authentication) in place, the client uses your configured key: ```ruby theme={null} client = Paubox::Client.new ``` Methods return the parsed JSON response as a hash with string keys. ## Domains ### List domains ```ruby theme={null} result = client.list_receiving_domains result['data'].each { |d| puts d['domain'] } ``` ### Create a domain ```ruby theme={null} result = client.create_receiving_domain(slug: 'support') puts result['data']['domain'] # => "support.inbound.paubox.email" ``` ### Get a domain ```ruby theme={null} result = client.get_receiving_domain(1) ``` ### Delete a domain ```ruby theme={null} client.delete_receiving_domain(1) ``` ## Mailboxes ### List mailboxes ```ruby theme={null} result = client.list_receiving_mailboxes(domain_id) ``` ### Create a mailbox ```ruby theme={null} result = client.create_receiving_mailbox(domain_id, name: 'intake', password: 'SecurePass123!' ) ``` ### Get / Delete a mailbox ```ruby theme={null} client.get_receiving_mailbox(domain_id, mailbox_id) client.delete_receiving_mailbox(domain_id, mailbox_id) ``` ## Emails ### List received emails ```ruby theme={null} result = client.list_received_emails(limit: 10) ``` ### Get a received email ```ruby theme={null} result = client.get_received_email(email_id) puts result['data']['text_body'] ``` ### Download an attachment ```ruby theme={null} attachment_id = result['data']['attachments'].first['id'] response = client.get_received_email_attachment(email_id, attachment_id) File.binwrite('report.pdf', response.body) ``` See the [Ruby SDK receiving client](/ruby-sdk/receiving-client) for the full reference — the methods are identical. # Rails SDK webhook client Source: https://docs.paubox.com/rails-sdk/webhook-client Create, list, get, update, and delete Paubox webhook endpoints with the Rails SDK to receive Email API and Forms events. > [!NOTE] > > Webhook endpoint methods require `paubox_rails` 1.2.0 or later. They are on `PauboxRails::Webhooks::Client`, not on `Paubox::Client` from the `paubox` gem. `PauboxRails::Webhooks::Client` manages webhook endpoints through the Paubox webhooks service at `https://api.paubox.com/v1/webhooks`. It sends a scoped API key as `Authorization: Bearer YOUR_API_KEY`. The key's scopes decide which events it can subscribe to. It doesn't use the `api_key` from `Paubox.configure`. ## Create the client ```ruby theme={null} webhooks = PauboxRails::Webhooks.client(api_key: 'YOUR_API_KEY') ``` When `api_key:` is omitted, the client reads the `PAUBOX_WEBHOOKS_API_KEY` environment variable. Pass `base_url:` or set `PAUBOX_WEBHOOKS_URL` to override the base URL. Every method raises `PauboxRails::Webhooks::MissingApiKeyError` before sending a request if no key is set. ## Events | Event | Required scope | Fires when | | - | - | - | | `api_mail_log_delivered` | `email_api` | An Email API message is delivered | | `api_mail_log_opened` | `email_api` | A delivered message is opened | | `api_mail_log_temporary_failure` | `email_api` | Delivery fails temporarily | | `api_mail_log_permanent_failure` | `email_api` | Delivery fails permanently | | `email.inbound.received` | `email_api`, with no sender-domain limit | Inbound mail is received | | `forms.submission.created` | `forms` | A form submission is received | The SDK doesn't check event names. The API returns 422 for an unknown event and 403 for an event the key isn't scoped for. Email API keys created in the Paubox Dashboard are limited to a sender domain, so subscribe to inbound mail in the Paubox Dashboard under [Settings > Webhooks](https://next.paubox.com/settings/webhooks). For payloads and signature verification, see [Webhooks](/email-api/webhooks). ## List webhook endpoints ```ruby theme={null} result = webhooks.list_webhook_endpoints(page: 1, items: 50) result['data'].each do |endpoint| puts "#{endpoint['id']} #{endpoint['target_url']} #{endpoint['status']}" end puts result['page_info']['count'] ``` `page:` and `items:` are optional. The result is the parsed response, with `data` and `page_info`; `page_info['count']` is the total number of endpoints, not the length of this page. Endpoints carrying an event the key isn't scoped for are left out. ## Create a webhook endpoint ```ruby theme={null} endpoint = webhooks.create_webhook_endpoint( target_url: 'https://example.com/webhooks/paubox', events: ['api_mail_log_delivered', 'api_mail_log_opened'] ) puts endpoint['id'] puts endpoint['signing_secret'] ``` `target_url:` must be an `https` URL that doesn't point at a private or internal address. Each endpoint is a hash with `id` (a UUID), `target_url`, `status` (`active` or `disabled`), `events`, `created_at`, and `updated_at`. `signing_secret` is returned only by this call; store it when you create the endpoint. To replace a lost secret, delete the endpoint and create a new one. ## Get a webhook endpoint ```ruby theme={null} endpoint = webhooks.get_webhook_endpoint('2ec66c21-bf48-48eb-8d28-f80b2d6b77c7') ``` ## Update a webhook endpoint ```ruby theme={null} endpoint = webhooks.update_webhook_endpoint('2ec66c21-bf48-48eb-8d28-f80b2d6b77c7', status: 'disabled') ``` Pass any of `target_url:`, `status:` (`'active'` or `'disabled'`), and `events:`. Only the arguments you pass are sent. `events:` replaces the endpoint's event list. ## Delete a webhook endpoint ```ruby theme={null} webhooks.delete_webhook_endpoint('2ec66c21-bf48-48eb-8d28-f80b2d6b77c7') ``` Returns `true`. ## Error handling ```ruby theme={null} begin webhooks.create_webhook_endpoint( target_url: 'https://example.com/webhooks/paubox', events: ['api_mail_log_delivered'] ) rescue PauboxRails::Webhooks::Error => e puts e.class puts e.message end ``` Errors are subclasses of `PauboxRails::Webhooks::Error`: `BadRequestError` (400 or 422), `UnauthorizedError` (401), `ForbiddenError` (403), and `NotFoundError` (404). Other statuses raise `PauboxRails::Webhooks::Error` itself, with the status code and raw response body in the message. For 400, 401, 403 and 422 the message is the API's error text; `NotFoundError` always says "Webhook endpoint not found". Creating a second endpoint for the same `target_url` raises `BadRequestError`, and an ID that isn't on your account raises `NotFoundError`. An ID that isn't a UUID raises `ArgumentError` before any request is sent. # Ruby SDK authentication Source: https://docs.paubox.com/ruby-sdk/authentication Configure Paubox API credentials for the Ruby SDK with global or per-client configuration, plus Forms client setup and key security notes. ## Obtain your credentials The Email API client requires one credential: * **API key**: a secret token that authenticates your requests It is available in the [Paubox dashboard](https://next.paubox.com) under **API Credentials**. ## Global configuration (recommended) Set your API key once at application startup. All `Paubox::Client` instances will use it automatically: ```ruby theme={null} require 'json' require 'paubox' Paubox.configure do |config| config.api_key = ENV['PAUBOX_API_KEY'] end client = Paubox::Client.new ``` ## Per-client configuration Override the API key for a specific client instance: ```ruby theme={null} client = Paubox::Client.new(api_key: 'YOUR_API_KEY') ``` `Paubox::Client.new` reads the global configuration even when you pass `api_key:`, so call `Paubox.configure` first. Without it, `Paubox::Client.new` raises `NoMethodError`. The SDK sets the `Authorization` header automatically on every request: ``` Authorization: Token token=YOUR_API_KEY ``` ## Forms client `get_form` and `submit_form` on `Paubox::FormsClient` require no credentials: ```ruby theme={null} forms_client = Paubox::FormsClient.new ``` The form management methods (for example `list_forms`, `create_form`, and `list_submissions`) require a scoped API key with the `forms` scope, sent as `Authorization: Bearer`. It can be the same key as the Email API key if that key also has the `forms` scope. Pass it to the constructor or set `config.forms_api_key`: ```ruby theme={null} forms_client = Paubox::FormsClient.new(api_key: 'YOUR_FORMS_API_KEY') ``` ## Security notes * Never hard-code credentials in source files; always read from environment variables. * The SDK does not log API keys or request bodies. # Ruby SDK email client Source: https://docs.paubox.com/ruby-sdk/email-client Full reference for the Paubox Ruby SDK email client: building messages, sending email, tracking delivery, dynamic templates, and error handling. ## The client ```ruby theme={null} client = Paubox::Client.new # uses global Paubox.configure credentials client = Paubox::Client.new(api_key: 'YOUR_API_KEY') # or a per-client API key ``` Call `Paubox.configure` before creating a client, even when you pass `api_key:`; see [Authentication](/ruby-sdk/authentication). `send_mail` and `deliver_mail` are aliases. `email_disposition` and `message_receipt` are aliases. ## Building a message ```ruby theme={null} message = Paubox::Message.new( from: 'sender@yourdomain.com', # required to: ['alice@example.com'], # required; array subject: 'Your results are ready', # optional reply_to: 'support@yourdomain.com', # optional cc: ['manager@example.com'], # optional bcc: ['audit@example.com'], # optional text_content: 'Plain text body.', # at least one required html_content: '<p>HTML body.</p>', # optional allow_non_tls: false, # optional; default false force_secure_notification: 'true' # optional; the string 'true' or 'false' ) ``` ### Attachments Attach files by path using the helper method. It detects the MIME type with the system `file` command: ```ruby theme={null} message.add_attachment('/path/to/report.pdf') ``` Or set the `attachments` attribute directly with an array of hashes, each with `fileName`, `contentType`, and `content`. The SDK base64-encodes `content`, so pass the raw file bytes: ```ruby theme={null} message.attachments = [ { fileName: 'report.pdf', contentType: 'application/pdf', content: File.binread('/path/to/report.pdf') } ] ``` ## Send a message ```ruby theme={null} response = client.send_mail(message) puts response['sourceTrackingId'] ``` ## Check delivery status ```ruby theme={null} disposition = client.email_disposition(source_tracking_id) disposition.message_deliveries.each do |delivery| puts "#{delivery.recipient} → #{delivery.status.delivery_status}" end ``` `EmailDisposition` fields: | Field | Description | | - | - | | `source_tracking_id` | The tracking ID | | `message_deliveries` | Array of `MessageDelivery` structs | | `errors` | Array of `ResponseError` structs | Each `MessageDelivery` struct has `recipient` and `status`. For a message with one recipient, the `status` struct has `delivery_status`, `delivery_time`, `opened_status` (`'unopened'` if not opened), and `opened_time`. For a message with more than one recipient, it has only `delivery_status` and `delivery_time`. Check `disposition.errors?` to detect API-level errors. Common `delivery_status` values: `delivered`, `delivered via secure portal`, `soft bounced`, `hard bounced`, `processing`. Opens are reported separately in `opened_status`. ## Scheduled send Schedule a message for future delivery, check its status, reschedule, or cancel it. ### Schedule a message ```ruby theme={null} require 'time' scheduled_at = (Time.now.utc + 24 * 60 * 60).iso8601 response = client.schedule_mail(message, scheduled_at) puts response['sourceTrackingId'] puts response['scheduledAt'] ``` `scheduled_at` must be an ISO 8601 UTC datetime string in the future and within 30 days. `schedule_mail` accepts a `Paubox::Message`, a `Mail::Message`, or a plain hash. It does not send templated messages. ### Get scheduled message status ```ruby theme={null} status = client.get_scheduled(source_tracking_id) puts status['state'] # "pending", "processing", "sent", "failed", "cancelled" puts status['scheduledAt'] ``` ### Reschedule a message ```ruby theme={null} new_time = (Time.now.utc + 2 * 24 * 60 * 60).iso8601 response = client.reschedule(source_tracking_id, new_time) puts response['scheduledAt'] ``` ### Cancel a scheduled message ```ruby theme={null} response = client.cancel_scheduled(source_tracking_id) puts response['state'] # "cancelled" ``` ## Dynamic templates Templates use [Handlebars](https://handlebarsjs.com) syntax (`{{variable_name}}`). The `Paubox::DynamicTemplates` methods always use the API key from `Paubox.configure`. ### Create a template ```ruby theme={null} Paubox::DynamicTemplates.create('appointment-confirmation', '/path/to/template.html') ``` ### List templates ```ruby theme={null} templates = Paubox::DynamicTemplates.list['templates'] templates.each { |t| puts "#{t['id']}: #{t['name']}" } ``` ### Get a template ```ruby theme={null} template = Paubox::DynamicTemplates.find(template_id) ``` ### Update a template ```ruby theme={null} template.update('/path/to/updated-template.html', template.name) # or rename: template.update('/path/to/updated-template.html', 'new-template-name') ``` Always pass a name. If you leave it out, the SDK sends an empty name and the API rejects the update with `name: can't be blank`. ### Delete a template ```ruby theme={null} template.delete ``` ### Send a templated message ```ruby theme={null} message = Paubox::TemplatedMessage.new( from: 'appointments@yourclinic.com', to: ['jane@example.com'], subject: 'Your appointment is confirmed', template: { name: 'appointment-confirmation', values: { first_name: 'Jane', date: '2024-03-15', time: '2:00 PM' } } ) response = client.send_mail(message) ``` ## Error handling `Paubox::Client` and `Paubox::DynamicTemplates` methods raise `RestClient::ExceptionWithResponse` on HTTP errors. Rescue the exception to inspect the response: ```ruby theme={null} require 'rest-client' begin response = client.send_mail(message) rescue RestClient::ExceptionWithResponse => e puts "HTTP #{e.response.code}: #{e.response.body}" end ``` # Ruby SDK forms client Source: https://docs.paubox.com/ruby-sdk/forms-client Retrieve Paubox Form schemas and submit form responses using the Ruby SDK. `get_form` and `submit_form` do not require API credentials. Forms are identified by a UUID that you obtain from the Paubox dashboard. The SDK checks the format and raises `ArgumentError` for a form ID that is not a UUID, before sending a request. The form management methods require a scoped API key; see [Manage forms](#manage-forms). ## Instantiation ```ruby theme={null} require 'json' require 'paubox' forms_client = Paubox::FormsClient.new ``` ## Get a form Retrieve a form's metadata, field schema, and rendered HTML/CSS: ```ruby theme={null} form = forms_client.get_form('your-form-uuid') puts form.title puts form.form_html ``` The returned `Paubox::Form` object exposes: | Method / Attribute | Description | | - | - | | `#title` | Display name of the form | | `#form_json` | Parsed field schema | | `#form_html` | Rendered HTML for embedding | | `#form_css` | Associated stylesheet | | `#active?` | Whether the form is accepting submissions | | `#submission_count` | Number of submissions received | | `#signable?` | Whether the form supports e-signatures | | `#archived?` | Whether the form is archived | ## Submit a form ```ruby theme={null} form_data = { first_name: 'Jane', last_name: 'Smith', email: 'jane@example.com' } response = forms_client.submit_form('your-form-uuid', form_data: form_data) # response is a RestClient::Response; response.code is 201 on success ``` ### Submitting with file attachments The maximum total request size is 250 MB. ```ruby theme={null} require 'base64' encoded = Base64.strict_encode64(File.read('consent.pdf')) attachments = [ { name: 'consent.pdf', content: encoded } ] response = forms_client.submit_form( 'your-form-uuid', form_data: form_data, attachments: attachments ) ``` ## Manage forms The management methods require a scoped API key with the `forms` scope, passed as `api_key:` or set with `config.forms_api_key`. It can be the same key as the Email API key if that key also has the `forms` scope. ```ruby theme={null} forms_client = Paubox::FormsClient.new(api_key: 'YOUR_FORMS_API_KEY') result = forms_client.list_forms(customer_id: 12345) result[:forms].each { |form| puts form.title } ``` Available methods: `find_form`, `list_forms` (requires `customer_id:`), `create_form`, `update_form`, `archive_form`, `unarchive_form`, `copy_form`, `form_stats`, `list_submissions`, `submissions_csv`, and `submission_pdf`. Calling one without a key raises `ArgumentError`. ## Error handling A non-2xx response raises `Paubox::FormsClient::Error`, which provides `status_code`, `url`, and `response_body`: ```ruby theme={null} begin form = forms_client.get_form('your-form-uuid') response = forms_client.submit_form('your-form-uuid', form_data: form_data) rescue ArgumentError => e puts "Invalid input: #{e.message}" rescue Paubox::FormsClient::Error => e puts "HTTP #{e.status_code}: #{e.response_body}" end ``` # Paubox Ruby SDK Source: https://docs.paubox.com/ruby-sdk/index Send HIPAA compliant email and submit Paubox Forms from Ruby applications using the official Paubox Ruby gem. The Paubox Ruby SDK (`paubox` gem) is the core Ruby client library for the [Paubox Email API](/email-api) and [Paubox Forms](/forms). It provides direct API access for sending and scheduling encrypted email, managing dynamic templates, tracking delivery, receiving inbound email, managing webhook endpoints, and working with forms. ```ruby theme={null} # Gemfile gem 'paubox' ``` ## What you can do * Send encrypted, HIPAA compliant email to one or more recipients * Create, update, and delete dynamic Handlebars templates * Send templated messages with per-message variable substitution * Track delivery status and open engagement per recipient * Schedule, reschedule, and cancel future sends * Manage receiving domains and mailboxes, and read inbound email and attachments * Manage webhook endpoints for Email API and Forms events * Retrieve Paubox Form schemas and submit form responses with file attachments ## Requirements * Ruby 2.5 or later * Dependencies installed automatically: `mail`, `rest-client`, `base64`, and `ostruct` ## Rails applications If you are using Rails, the [`paubox_rails`](/rails-sdk) gem builds on top of this library and adds ActionMailer integration. Use `paubox` directly for non-Rails Ruby applications, scripts, or background jobs. ## Get started > [card] [Quickstart](/ruby-sdk/quickstart) > > Configure credentials and send your first email in minutes. > [card] [Authentication](/ruby-sdk/authentication) > > Configure globally or per-client with your API key. > [card] [Email client](/ruby-sdk/email-client) > > Full reference for sending email, managing templates, and tracking delivery. > [card] [Forms client](/ruby-sdk/forms-client) > > Retrieve form schemas and submit responses. # Ruby SDK quickstart Source: https://docs.paubox.com/ruby-sdk/quickstart Install the Paubox Ruby gem and send your first HIPAA compliant email in minutes. **1. Install the gem** Add to your Gemfile: ```ruby theme={null} gem 'paubox' ``` Then install: ```bash theme={null} bundle install ``` Or install directly: ```bash theme={null} gem install paubox ``` **2. Configure credentials** ```ruby theme={null} require 'json' require 'paubox' Paubox.configure do |config| config.api_key = ENV['PAUBOX_API_KEY'] end ``` To obtain your API key, see [Authentication](/ruby-sdk/authentication). **3. Send your first email** ```ruby theme={null} client = Paubox::Client.new message = Paubox::Message.new( from: 'sender@yourdomain.com', to: ['recipient@example.com'], subject: 'Your first Paubox email', text_content: 'This message was sent with the Paubox Ruby SDK.' ) response = client.send_mail(message) puts "Sent. Tracking ID: #{response['sourceTrackingId']}" ``` **4. Check delivery status** ```ruby theme={null} tracking_id = response['sourceTrackingId'] disposition = client.email_disposition(tracking_id) disposition.message_deliveries.each do |delivery| puts "#{delivery.recipient} → #{delivery.status.delivery_status}" end ``` ## Next steps * [Email client](/ruby-sdk/email-client): attachments, dynamic templates, error handling * [Forms client](/ruby-sdk/forms-client): retrieve form schemas and submit responses # Ruby SDK receiving client Source: https://docs.paubox.com/ruby-sdk/receiving-client Full reference for the Paubox Ruby SDK receiving API: managing domains, mailboxes, and retrieving inbound email. The receiving methods are on the same `Paubox::Client` you use to send email. ```ruby theme={null} require 'json' require 'paubox' Paubox.configure do |config| config.api_key = 'YOUR_API_KEY' end client = Paubox::Client.new ``` Methods return the parsed JSON response as a hash with string keys. ## Domains ### List domains ```ruby theme={null} result = client.list_receiving_domains result['data'].each { |d| puts d['domain'] } ``` ### Create a domain ```ruby theme={null} result = client.create_receiving_domain(slug: 'support') puts result['data']['domain'] # => "support.inbound.paubox.email" ``` Omit `slug:` to auto-generate one. ### Get a domain ```ruby theme={null} result = client.get_receiving_domain(1) ``` ### Delete a domain ```ruby theme={null} client.delete_receiving_domain(1) ``` ## Mailboxes ### List mailboxes ```ruby theme={null} result = client.list_receiving_mailboxes(domain_id) ``` ### Create a mailbox ```ruby theme={null} result = client.create_receiving_mailbox(domain_id, name: 'intake', password: 'SecurePass123!' ) puts result['data']['email_address'] # => "intake@support.inbound.paubox.email" ``` Pass `quota_bytes:` to set a storage quota. ### Get a mailbox ```ruby theme={null} result = client.get_receiving_mailbox(domain_id, mailbox_id) ``` ### Delete a mailbox ```ruby theme={null} client.delete_receiving_mailbox(domain_id, mailbox_id) ``` ## Emails ### List received emails ```ruby theme={null} result = client.list_received_emails(limit: 10) result['data'].each { |e| puts "#{e['email_id']}: #{e['subject']}" } # Cursor pagination; search:, sort:, and ascending: are also accepted next_page = client.list_received_emails(after: result['data'].last['email_id']) ``` ### Get a received email ```ruby theme={null} result = client.get_received_email(email_id) puts result['data']['text_body'] ``` ### Download an attachment ```ruby theme={null} email = client.get_received_email(email_id) attachment_id = email['data']['attachments'].first['id'] response = client.get_received_email_attachment(email_id, attachment_id) File.binwrite('report.pdf', response.body) ``` The attachment ID is the `id` of an entry in the email's `attachments`. The response is the raw `RestClient::Response`; call `.body` for the bytes. # Ruby SDK webhook client Source: https://docs.paubox.com/ruby-sdk/webhook-client Create, list, get, update, and delete Paubox webhook endpoints with the Ruby SDK to receive Email API and Forms events. > [!NOTE] > > Webhook endpoint methods require `paubox` 2.0.0 or later. They are on `Paubox::WebhooksClient`, not on the `Paubox::Client` you use to send email. `Paubox::WebhooksClient` manages webhook endpoints through the Paubox webhooks service at `https://api.paubox.com/v1/webhooks`. It sends a scoped API key as `Authorization: Bearer YOUR_API_KEY`. The key's scopes decide which events it can subscribe to. ## Create the client ```ruby theme={null} require 'paubox' webhooks = Paubox::WebhooksClient.new(api_key: 'YOUR_API_KEY') ``` When `api_key:` is omitted, the client uses `webhooks_api_key` from `Paubox.configure`: ```ruby theme={null} Paubox.configure do |config| config.webhooks_api_key = 'YOUR_API_KEY' end webhooks = Paubox::WebhooksClient.new ``` Every method raises `ArgumentError` before sending a request if no key is set. ## Events | Event | Required scope | Fires when | | - | - | - | | `api_mail_log_delivered` | `email_api` | An Email API message is delivered | | `api_mail_log_opened` | `email_api` | A delivered message is opened | | `api_mail_log_temporary_failure` | `email_api` | Delivery fails temporarily | | `api_mail_log_permanent_failure` | `email_api` | Delivery fails permanently | | `email.inbound.received` | `email_api`, with no sender-domain limit | Inbound mail is received | | `forms.submission.created` | `forms` | A form submission is received | The SDK doesn't check event names. The API returns 422 for an unknown event and 403 for an event the key isn't scoped for. Email API keys created in the Paubox Dashboard are limited to a sender domain, so subscribe to inbound mail in the Paubox Dashboard under [Settings > Webhooks](https://next.paubox.com/settings/webhooks). For payloads and signature verification, see [Webhooks](/email-api/webhooks). ## List webhook endpoints ```ruby theme={null} result = webhooks.list_webhook_endpoints(page: 1, items: 50) result['data'].each do |endpoint| puts "#{endpoint['id']} #{endpoint['target_url']} #{endpoint['status']}" end puts result['page_info']['count'] ``` `page:` and `items:` are optional. The result is the parsed response, with `data` and `page_info`; `page_info['count']` is the total number of endpoints, not the length of this page. Endpoints carrying an event the key isn't scoped for are left out. ## Create a webhook endpoint ```ruby theme={null} endpoint = webhooks.create_webhook_endpoint( target_url: 'https://example.com/webhooks/paubox', events: ['api_mail_log_delivered', 'api_mail_log_opened'] ) puts endpoint['id'] puts endpoint['signing_secret'] ``` `target_url:` must be an `https` URL that doesn't point at a private or internal address. Each endpoint is a hash with `id` (a UUID), `target_url`, `status` (`active` or `disabled`), `events`, `created_at`, and `updated_at`. `signing_secret` is returned only by this call; store it when you create the endpoint. To replace a lost secret, delete the endpoint and create a new one. ## Get a webhook endpoint ```ruby theme={null} endpoint = webhooks.get_webhook_endpoint('2ec66c21-bf48-48eb-8d28-f80b2d6b77c7') ``` ## Update a webhook endpoint ```ruby theme={null} endpoint = webhooks.update_webhook_endpoint('2ec66c21-bf48-48eb-8d28-f80b2d6b77c7', status: 'disabled') ``` Pass any of `target_url:`, `status:` (`'active'` or `'disabled'`), and `events:`. Only the arguments you pass are sent. `events:` replaces the endpoint's event list. ## Delete a webhook endpoint ```ruby theme={null} webhooks.delete_webhook_endpoint('2ec66c21-bf48-48eb-8d28-f80b2d6b77c7') ``` Returns `true`. ## Error handling ```ruby theme={null} begin webhooks.create_webhook_endpoint( target_url: 'https://example.com/webhooks/paubox', events: ['api_mail_log_delivered'] ) rescue Paubox::WebhooksClient::Error => e puts e.status_code puts e.message end ``` A non-2xx response raises `Paubox::WebhooksClient::Error` with the API's error text as its message, plus `status_code`, `url`, and `response_body`. Creating a second endpoint for the same `target_url` returns 422, and an ID that isn't on your account returns 404. An ID that isn't a UUID raises `ArgumentError` before any request is sent. # Rust SDK authentication Source: https://docs.paubox.com/rust-sdk/authentication Configure Paubox API credentials for the Rust SDK with environment variables, a direct constructor, or a builder with custom timeout and base URL. ## Obtain your credentials The Email API client requires one credential: * **API key**: a secret token that authenticates your requests It is available in the [Paubox dashboard](https://next.paubox.com) under **API Credentials**. ## Option 1: Environment variables (recommended) ```bash theme={null} export PAUBOX_API_KEY="YOUR_API_KEY" ``` ```rust theme={null} let client = PauboxClient::from_env()?; ``` `from_env()` returns `Err(PauboxError::EnvVar(...))` immediately if the variable is missing or empty. ## Option 2: Direct constructor ```rust theme={null} let client = PauboxClient::new("YOUR_API_KEY"); ``` ## Option 3: Builder (with custom timeout or base URL) ```rust theme={null} use std::time::Duration; let client = PauboxClient::builder() .api_key("YOUR_API_KEY") .timeout(Duration::from_secs(15)) .build()?; ``` Use `.base_url(url)` in tests to point at a mock server. The SDK sets the `Authorization` header automatically on every request: ``` Authorization: Token token=YOUR_API_KEY ``` ## Forms client `FormsClient` requires no credentials: ```rust theme={null} let forms = FormsClient::new(); ``` If you already have a `PauboxClient`, reuse its HTTP connection pool: ```rust theme={null} let forms = email_client.forms(); ``` ## Security notes * Never hard-code credentials in source files. * The SDK does not log API keys or request bodies. # Rust SDK email client Source: https://docs.paubox.com/rust-sdk/email-client Full reference for the Paubox Rust SDK email client: building messages, sending email, tracking delivery, and error handling. ## Creating a client ```rust theme={null} // From environment variables (recommended) let client = PauboxClient::from_env()?; // Direct constructor let client = PauboxClient::new("YOUR_API_KEY"); // Builder (custom timeout, base URL for testing) let client = PauboxClient::builder() .api_key("YOUR_API_KEY") .timeout(Duration::from_secs(15)) .build()?; ``` See [Authentication](/rust-sdk/authentication) for details on all three options. ## Building a message Use `Message::builder()` to compose a message. All methods take `impl Into<String>` or iterables: ```rust theme={null} use paubox::email::Message; let message = Message::builder() .from("sender@yourdomain.com") // required .to(["alice@example.com"]) // required; accepts any iterable .subject("Your results are ready") // required .text_content("Plain text body.") // at least one of text/html required .html_content("<p>HTML body.</p>") // optional .reply_to("support@yourdomain.com") // optional .cc(["manager@example.com"]) // optional .bcc(["audit@example.com"]) // optional .allow_non_tls(false) // optional; default false .force_secure_notification(true) // optional .build()?; ``` `.build()` returns `Err(PauboxError::Validation(...))` if `from`, `to`, or `subject` is missing. It doesn't check that a text or HTML body is set. ### Attachments The `from_bytes` constructor base64-encodes the data automatically; no manual encoding needed: ```rust theme={null} use paubox::email::Attachment; use std::fs; let data = fs::read("report.pdf")?; let attachment = Attachment::from_bytes("report.pdf", "application/pdf", &data); ``` If you already have base64-encoded content: ```rust theme={null} let attachment = Attachment::from_base64("report.pdf", "application/pdf", encoded_string); ``` Add attachments to a message via the builder: ```rust theme={null} let message = Message::builder() // ...other fields... .attachment(attachment) .build()?; ``` ## Send a message ```rust theme={null} let response = client.send_message(&message).await?; println!("Tracking ID: {}", response.source_tracking_id); ``` `SendResponse` fields: | Field | Description | | - | - | | `source_tracking_id` | Use to check delivery status | | `message` | Status message from the API | ## Check delivery status ```rust theme={null} let disposition = client .get_email_disposition(&response.source_tracking_id) .await?; for delivery in &disposition.message_deliveries { println!( "{} → {} (opened: {})", delivery.recipient, delivery.delivery_status, delivery.opened_status ); } ``` `MessageDelivery` fields: | Field | Description | | - | - | | `recipient` | Email address | | `delivery_status` | e.g. `delivered`, `delivered via secure portal`, `soft bounced`, `hard bounced`, `processing` | | `delivery_time` | RFC 2822 timestamp, if delivered | | `opened_status` | `opened` once the message has been opened | | `opened_time` | RFC 2822 timestamp, if opened | In paubox 1.3.1 through 2.0.0, `get_email_disposition` returns `PauboxError::Deserialize` for a delivered message that hasn't been opened yet, because the API sends `openedStatus` as `null` until the first open. The call succeeds once the message is opened, and for statuses that carry no open data, such as `processing` or a bounce. ## Scheduled send Schedule a message for future delivery, check its status, reschedule, or cancel it. ### Schedule a message ```rust theme={null} let scheduled_at = (chrono::Utc::now() + chrono::Duration::days(1)).to_rfc3339(); let response = client .schedule_message(&message, &scheduled_at) .await?; println!("Tracking ID: {}", response.source_tracking_id); println!("Scheduled for: {}", response.scheduled_at); ``` `scheduled_at` must be an ISO 8601 UTC datetime string in the future and within 30 days. The examples compute it with the [`chrono`](https://crates.io/crates/chrono) crate; add `chrono = "0.4"` to your dependencies, or pass any timestamp string you already have. ### Get scheduled message status ```rust theme={null} let status = client.get_scheduled_message("source-tracking-id").await?; println!("State: {}", status.state); // "pending", "processing", "sent", "failed", "cancelled" println!("Scheduled for: {}", status.scheduled_at); ``` `ScheduledMessageStatus` fields: | Field | Description | | - | - | | `source_tracking_id` | Tracking ID | | `scheduled_at` | Scheduled delivery time | | `state` | `pending`, `processing`, `sent`, `failed`, `cancelled` | | `message_id` | Internal message ID | ### Reschedule a message ```rust theme={null} let new_time = (chrono::Utc::now() + chrono::Duration::days(2)).to_rfc3339(); let response = client .reschedule_message("source-tracking-id", &new_time) .await?; println!("Rescheduled to: {}", response.scheduled_at); ``` ### Cancel a scheduled message ```rust theme={null} let response = client .cancel_scheduled_message("source-tracking-id") .await?; println!("Cancelled: {} (state: {})", response.source_tracking_id, response.state); ``` ## Health check In paubox 1.3.1 through 2.0.0, `client.api_status()` sends `GET` to the base URL (`https://api.paubox.com/v1/email/`), which isn't an API route, so it returns a `PauboxError` even when the API is reachable. Don't use it as a health check. ## Error handling All methods return `Result<T, PauboxError>`. Match on the variants to handle specific conditions: ```rust theme={null} use paubox::PauboxError; match client.send_message(&message).await { Ok(response) => println!("Sent: {}", response.source_tracking_id), Err(PauboxError::Auth(msg)) => eprintln!("Invalid credentials: {}", msg), Err(PauboxError::Http { status, body }) => { eprintln!("HTTP {}: {}", status, body); } Err(PauboxError::Validation(msg)) => eprintln!("Invalid message: {}", msg), Err(e) => eprintln!("Error: {}", e), } ``` `PauboxError` variants: | Variant | When it occurs | | - | - | | `Auth(String)` | HTTP 401: invalid or missing credentials | | `Http { status, body }` | Non-2xx response other than 401 | | `Request(reqwest::Error)` | Network or TLS failure | | `Deserialize(serde_json::Error)` | Unexpected response format | | `Validation(String)` | Missing required message field | | `EnvVar(String)` | Missing environment variable in `from_env()` | | `Url(url::ParseError)` | URL construction failure | # Rust SDK forms client Source: https://docs.paubox.com/rust-sdk/forms-client Submit Paubox Form responses, with file attachments, using the Rust SDK. The Forms client submits form responses and does not require API credentials. Forms are identified by a UUID that you obtain from the Paubox dashboard. ## Creating a client **Standalone** (creates its own HTTP connection pool): ```rust theme={null} use paubox::forms::FormsClient; let client = FormsClient::new(); ``` **Shared connection pool** (reuses the HTTP client from an existing `PauboxClient`): ```rust theme={null} let forms = email_client.forms(); ``` ## Submit a form Build a `FormSubmission` and call `submit_form`: ```rust theme={null} use paubox::forms::FormSubmission; use serde_json::json; let submission = FormSubmission::builder() .form_data(json!({ "first_name": "Jane", "last_name": "Smith", "email": "jane@example.com" })) .build()?; client.submit_form("your-form-uuid", &submission).await?; ``` `submit_form` returns `Ok(())` on success (HTTP 201). ### Submitting with file attachments The maximum total request size is 250 MB. `FormAttachment::from_bytes` base64-encodes automatically: ```rust theme={null} use paubox::forms::{FormAttachment, FormSubmission}; use std::fs; let data = fs::read("consent.pdf")?; let attachment = FormAttachment::from_bytes("consent.pdf", &data); let submission = FormSubmission::builder() .form_data(json!({ "first_name": "Jane" })) .attachment(attachment) .build()?; client.submit_form("your-form-uuid", &submission).await?; ``` If you already have base64-encoded content: ```rust theme={null} let attachment = FormAttachment::from_base64("consent.pdf", encoded_string); ``` ## Error handling ```rust theme={null} use paubox::PauboxError; match client.submit_form("your-form-uuid", &submission).await { Ok(()) => println!("Submitted"), Err(PauboxError::Http { status, body }) => { eprintln!("HTTP {}: {}", status, body); } Err(e) => eprintln!("Error: {}", e), } ``` # Paubox Rust SDK Source: https://docs.paubox.com/rust-sdk/index Send HIPAA compliant email and submit Paubox Forms from Rust applications using the official Paubox Rust SDK. The Paubox Rust SDK is the official async Rust client library for the [Paubox Email API](/email-api) and [Paubox Forms](/forms). All methods are `async` and return `Result<T, PauboxError>`, making them composable with any Tokio-based application. ```toml theme={null} # Cargo.toml [dependencies] paubox = "2.0" tokio = { version = "1", features = ["rt-multi-thread", "macros"] } ``` ## What you can do * Send encrypted, HIPAA compliant email to one or more recipients * Add CC, BCC, attachments, and HTML or plain-text content * Track delivery status and open engagement per recipient * Schedule, reschedule, and cancel future sends * Manage receiving domains and mailboxes, and read inbound email and attachments * Manage webhook endpoints for Email API and Forms events * Submit Paubox Form responses with file attachments ## Requirements * Rust 1.88 or later * Tokio async runtime ## Feature flags All three features are enabled by default. Disable the ones you don't need to reduce compile times: ```toml theme={null} # Email API only paubox = { version = "2.0", default-features = false, features = ["email"] } # Forms API only paubox = { version = "2.0", default-features = false, features = ["forms"] } ``` | Feature | What it includes | | - | - | | `email` | `PauboxClient`, `paubox::email`, `paubox::receiving` | | `forms` | `paubox::forms` (`FormsClient`, `FormSubmission`, `FormAttachment`) | | `webhooks` | `paubox::webhooks` (`WebhooksClient`) | ## Get started > [card] [Quickstart](/rust-sdk/quickstart) > > Configure credentials and send your first email in minutes. > [card] [Authentication](/rust-sdk/authentication) > > Three ways to supply your API key. > [card] [Email client](/rust-sdk/email-client) > > Full reference for building messages, sending email, and tracking delivery. > [card] [Forms client](/rust-sdk/forms-client) > > Submit form responses. # Rust SDK quickstart Source: https://docs.paubox.com/rust-sdk/quickstart Install the Paubox Rust SDK and send your first HIPAA compliant email in minutes. **1. Add the dependency** Add `paubox` and `tokio` to your `Cargo.toml`: ```toml theme={null} [dependencies] paubox = "2.0" tokio = { version = "1", features = ["rt-multi-thread", "macros"] } ``` **2. Set your credentials** Export your API key as an environment variable: ```bash theme={null} export PAUBOX_API_KEY="YOUR_API_KEY" ``` To obtain your API key, see [Authentication](/rust-sdk/authentication). **3. Send your first email** Create `src/main.rs`: ```rust theme={null} use paubox::{email::Message, PauboxClient}; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let client = PauboxClient::from_env()?; let message = Message::builder() .from("sender@yourdomain.com") .to(["recipient@example.com"]) .subject("Your first Paubox email") .text_content("This message was sent with the Paubox Rust SDK.") .build()?; let response = client.send_message(&message).await?; println!("Sent. Tracking ID: {}", response.source_tracking_id); Ok(()) } ``` Run it: ```bash theme={null} cargo run ``` ``` Sent. Tracking ID: abc123-def456-... ``` **4. Check delivery status** ```rust theme={null} let disposition = client .get_email_disposition(&response.source_tracking_id) .await?; for delivery in &disposition.message_deliveries { println!("{} → {}", delivery.recipient, delivery.delivery_status); } ``` ``` recipient@example.com → delivered ``` In paubox 1.3.1 through 2.0.0, this call returns a `Deserialize` error for a delivered message that hasn't been opened yet. See [Check delivery status](/rust-sdk/email-client#check-delivery-status). ## Next steps * [Email client](/rust-sdk/email-client): attachments, CC/BCC, error handling * [Forms client](/rust-sdk/forms-client): submit form responses # Rust SDK receiving client Source: https://docs.paubox.com/rust-sdk/receiving-client Full reference for the Paubox Rust SDK receiving API: managing domains, mailboxes, and retrieving inbound email. The receiving methods are on the same `PauboxClient` you use to send email. They require the `email` feature (enabled by default). ```rust theme={null} let client = PauboxClient::new("YOUR_API_KEY"); ``` All methods are async and return `Result<T, PauboxError>`. ## Domains ### List domains ```rust theme={null} let domains = client.list_receiving_domains().await?; for d in &domains { println!("{}", d.domain.as_deref().unwrap_or("")); } ``` ### Create a domain ```rust theme={null} let domain = client.create_receiving_domain(Some("support")).await?; println!("{}", domain.domain.as_deref().unwrap_or("")); // support.inbound.paubox.email ``` Pass `None` to auto-generate a slug. ### Get a domain ```rust theme={null} let domain = client.get_receiving_domain(1).await?; ``` ### Delete a domain ```rust theme={null} client.delete_receiving_domain(1).await?; ``` ## Mailboxes ### List mailboxes ```rust theme={null} let mailboxes = client.list_receiving_mailboxes(domain_id).await?; ``` ### Create a mailbox ```rust theme={null} let mailbox = client.create_receiving_mailbox(domain_id, "intake", "SecurePass123!", None).await?; println!("{}", mailbox.email_address.unwrap_or_default()); ``` Pass `Some(bytes)` as the fourth argument for a storage quota. ### Get a mailbox ```rust theme={null} let mailbox = client.get_receiving_mailbox(domain_id, mailbox_id).await?; ``` ### Delete a mailbox ```rust theme={null} client.delete_receiving_mailbox(domain_id, mailbox_id).await?; ``` ## Emails ### List received emails ```rust theme={null} let resp = client.list_received_emails(Some(10), None, None).await?; for e in &resp.data { println!("{}: {}", e.email_id, e.subject.as_deref().unwrap_or("")); } // Cursor pagination let next = client.list_received_emails( None, resp.data.last().map(|e| e.email_id.as_str()), None, ).await?; ``` ### Get a received email ```rust theme={null} let email = client.get_received_email(email_id).await?; println!("{}", email.text_body.as_deref().unwrap_or("")); ``` ### Download an attachment The attachment ID is the `id` of an entry in the email's `attachments`. ```rust theme={null} let attachment = &email.attachments[0]; let data: Vec<u8> = client .get_received_email_attachment(&email.email_id, &attachment.id) .await?; std::fs::write("report.pdf", &data)?; ``` # Rust SDK webhook client Source: https://docs.paubox.com/rust-sdk/webhook-client Create, list, get, update, and delete Paubox webhook endpoints with the Rust SDK to receive Email API and Forms events. > [!NOTE] > > Webhook endpoint methods require SDK 2.0.0 or later. They are on `paubox::webhooks::WebhooksClient`, not on the `PauboxClient` you use to send email. `WebhooksClient` manages webhook endpoints through the Paubox webhooks service at `https://api.paubox.com/v1/webhooks`. It sends a scoped API key as `Authorization: Bearer YOUR_API_KEY`. The key's scopes decide which events it can subscribe to. It requires the `webhooks` feature (enabled by default). ## Create the client ```rust theme={null} use paubox::webhooks::WebhooksClient; let webhooks = WebhooksClient::new("YOUR_API_KEY"); ``` `WebhooksClient::with_base_url(api_key, url)` overrides the base URL with a `url::Url`, and `WebhooksClient::with_http(api_key, http)` uses your own `reqwest::Client`. The client doesn't read an environment variable. All methods are async and return `Result<T, PauboxError>`. ## Events | Event | Required scope | Fires when | | - | - | - | | `api_mail_log_delivered` | `email_api` | An Email API message is delivered | | `api_mail_log_opened` | `email_api` | A delivered message is opened | | `api_mail_log_temporary_failure` | `email_api` | Delivery fails temporarily | | `api_mail_log_permanent_failure` | `email_api` | Delivery fails permanently | | `email.inbound.received` | `email_api`, with no sender-domain limit | Inbound mail is received | | `forms.submission.created` | `forms` | A form submission is received | The SDK doesn't check event names. The API returns 422 for an unknown event and 403 for an event the key isn't scoped for. Email API keys created in the Paubox Dashboard are limited to a sender domain, so subscribe to inbound mail in the Paubox Dashboard under [Settings > Webhooks](https://next.paubox.com/settings/webhooks). For payloads and signature verification, see [Webhooks](/email-api/webhooks). ## List webhook endpoints ```rust theme={null} use paubox::webhooks::ListWebhookEndpointsParams; let list = webhooks .list_webhook_endpoints(&ListWebhookEndpointsParams { page: Some(1), items: Some(50), }) .await?; for endpoint in &list.data { println!("{} {} {}", endpoint.id, endpoint.target_url, endpoint.status); } println!("{}", list.page_info.count); ``` Pass `&ListWebhookEndpointsParams::default()` for the first page. `page_info.count` is the total number of endpoints, not the length of `data`. Endpoints carrying an event the key isn't scoped for are left out. ## Create a webhook endpoint ```rust theme={null} let created = webhooks .create_webhook_endpoint( "https://example.com/webhooks/paubox", &["api_mail_log_delivered", "api_mail_log_opened"], ) .await?; println!("{}", created.endpoint.id); println!("{}", created.signing_secret); ``` The target URL must be an `https` URL that doesn't point at a private or internal address. `create_webhook_endpoint` returns a `CreatedWebhookEndpoint`, with the endpoint in `endpoint` and the secret in `signing_secret`. `WebhookEndpoint` has `id` (a UUID), `target_url`, `status` (`active` or `disabled`), `events`, `created_at`, and `updated_at`. The signing secret is returned only by this call; store it when you create the endpoint. To replace a lost secret, delete the endpoint and create a new one. ## Get a webhook endpoint ```rust theme={null} let endpoint = webhooks .get_webhook_endpoint("2ec66c21-bf48-48eb-8d28-f80b2d6b77c7") .await?; ``` ## Update a webhook endpoint ```rust theme={null} use paubox::webhooks::UpdateWebhookEndpoint; let updated = webhooks .update_webhook_endpoint( "2ec66c21-bf48-48eb-8d28-f80b2d6b77c7", UpdateWebhookEndpoint { status: Some("disabled".into()), ..Default::default() }, ) .await?; ``` `UpdateWebhookEndpoint` has optional `target_url`, `status` (`"active"` or `"disabled"`), and `events` fields. Only the fields you set are sent. `events` replaces the endpoint's event list. ## Delete a webhook endpoint ```rust theme={null} webhooks .delete_webhook_endpoint("2ec66c21-bf48-48eb-8d28-f80b2d6b77c7") .await?; ``` ## Error handling ```rust theme={null} use paubox::PauboxError; match webhooks .create_webhook_endpoint("https://example.com/webhooks/paubox", &["api_mail_log_delivered"]) .await { Ok(created) => println!("{}", created.endpoint.id), Err(PauboxError::Http { status, body }) => eprintln!("{status}: {body}"), Err(PauboxError::Auth(message)) => eprintln!("401: {message}"), Err(e) => eprintln!("{e}"), } ``` A 401 returns `PauboxError::Auth`; any other non-2xx response returns `PauboxError::Http`. Both carry the API's error text. Creating a second endpoint for the same target URL returns 422, and an ID that isn't on your account returns 404. An ID that isn't a UUID returns `PauboxError::Validation` before any request is sent. # SDKs Source: https://docs.paubox.com/sdks Official Paubox client libraries for the Email API and Forms API in C#, Go, Java, Node.js, Perl, PHP, Python, Rails, Ruby, and Rust. Paubox provides official SDKs for nine languages. Each library handles authentication, request formatting, and error handling so you can integrate in minutes. > [card] [C#](/csharp-sdk/index) > [card] [Go](/go-sdk/index) > [card] [Java](/java-sdk/index) > [card] [Node.js](/node-sdk/index) > [card] [Perl](/perl-sdk/index) > [card] [PHP](/php-sdk/index) > [card] [Python](/python-sdk/index) > [card] [Rails](/rails-sdk/index) > [card] [Ruby](/ruby-sdk/index) > [card] [Rust](/rust-sdk/index) Source code and issue trackers for all SDKs are available on [GitHub](https://github.com/paubox). # Introduction Source: https://docs.paubox.com/welcome HIPAA compliant, HITRUST certified email infrastructure. Send transactional email, run marketing campaigns, and collect patient data with forms. ## Which product is right for me? | I want to… | Use… | | :- | :- | | Send transactional email from my app | [Email API](/email-api/quickstart) | | Run email campaigns to patient lists | [Marketing API](/marketing) | | Collect patient intake or consent data | [Forms API](/forms/index) | | Send email from the terminal | [CLI](/cli/quickstart) | | Use Paubox from Claude or AI agents | [MCP Server](/mcp-server/quickstart) | | Use Paubox from my app (Go, Node, Python, etc.) | [SDKs](/sdks) | ## Products > [card] [Email API](/email-api) > > Send transactional, HIPAA compliant email via REST or SMTP > [card] [Marketing API](/marketing) > > Campaigns, drip sequences, subscribers, and analytics > [card] [Forms API](/forms/index) > > Collect patient data via HIPAA compliant secure forms > [card] [CLI](/cli/index) > > Send email and check delivery from the terminal > [card] [MCP Server](/mcp-server/index) > > Give AI assistants access to Paubox Email, Marketing, and Forms tools ## Get started > [card] [Quickstart guide](/email-api/quickstart) > > Four steps to your first email > [card] [API conventions](/email-api) > > Auth, formatting, and response codes > [card] [REST API](/email-api/messages) > > Send email via HTTP > [card] [SMTP API](/email-api/smtp) > > Send email via SMTP ## Quickstart by language > [card] [C#](/csharp-sdk/quickstart) > [card] [Go](/go-sdk/quickstart) > [card] [Java](/java-sdk/quickstart) > [card] [Node.js](/node-sdk/quickstart) > [card] [Perl](/perl-sdk/quickstart) > [card] [PHP](/php-sdk/quickstart) > [card] [Python](/python-sdk/quickstart) > [card] [Rails](/rails-sdk/quickstart) > [card] [Ruby](/ruby-sdk/quickstart) > [card] [Rust](/rust-sdk/quickstart) ## Building an SDK or integration? Start with our OpenAPI specs: point your generator, AI agent, or editor at them directly. > [card] [Email API OpenAPI spec](/openapi1.yaml) > > Transactional email: `api.paubox.com/v1/email` > [card] [Marketing API OpenAPI spec](/openapi2.yaml) > > Campaigns, subscribers, analytics: `api.paubox.com/v1/marketing` ## Need help? > [card] [GitHub](https://github.com/Paubox) > > SDK source and issues > [card] [Status](https://status.paubox.com) > > System uptime > [card] [Support](https://www.paubox.com/contact-us) > > Contact the team Have a question, an idea, or something you built to show off? Join the [Paubox Community](https://github.com/Paubox/community/discussions), the single home for discussions across every Paubox SDK and API (Email API, Forms, Marketing, and the MCP/CLI tooling). Never post PHI, recipient addresses, or message content in public threads. Anything sensitive goes to [support@paubox.com](mailto:support@paubox.com).