# API Versioning & Migration Source: https://docs.sendpost.io/api-reference/api-versioning How the SendPost response contract is versioned, how to migrate from the legacy shape to v1, and the deprecation timeline. SendPost is introducing a **versioned response contract** for the public REST API. This page explains what is changing, how to opt in, and the timeline. > [!NOTE] > > **Nothing changes for your integration today.** The **legacy** response shape stays the default until the sunset date below, so existing integrations keep working unchanged. You migrate to **v1** on your own schedule. ## The two contracts * **`legacy`** (default) — the exact response shape SendPost returns today. Requests that do not opt in keep receiving this until the sunset date. * **`v1`** — the new, normalized public contract: consistent camelCase field names, internal-only fields removed, and a few additive fields. Select the contract **per request** with a header: ``` X-SendPost-Public-Contract: v1 ``` Omit the header (or send `legacy`) to keep today's shape. The header works on every public `/api/v1/...` endpoint. ## Deprecation headers Every response advertises the contract state so your client and SDKs can track the migration: | Header | Meaning | | - | - | | `X-SendPost-Public-Contract` | the contract applied to this response — `legacy` or `v1` | | `Deprecation` | `true` while `legacy` is still served by default | | `Sunset` | the date after which **`v1` becomes the default** | | `Link` | a link to this migration guide (`rel="deprecation"`) | ## Timeline > [!WARNING] > > **Sunset: 31 March 2027, 23:59:59 UTC.** After this date, requests that do **not** send `X-SendPost-Public-Contract` receive the **`v1`** shape by default. Migrate your integration and pin `v1` before then. * **Now → sunset** — `legacy` is the default. Opt into `v1` any time with the header. * **After sunset** — `v1` becomes the default. Sending `X-SendPost-Public-Contract: v1` explicitly is still recommended so your integration is pinned and unaffected by future defaults. ## What changes in v1 `v1` normalizes the public response shape. The changes fall into three categories: 1. **Consistent camelCase.** Several fields used non-standard casing; `v1` normalizes them. Examples: * IP / message / event: `publicIP` → `publicIp`, `messageID` → `messageId`, `eventID` → `eventId` * Provider stats: `email_type` → `emailType` (Suppression's `smtpError` is already camelCase and is **not** renamed.) 2. **Internal fields removed.** Fields that were never part of the public contract — internal identifiers, infrastructure details, and any sensitive values — are not returned in `v1`. 3. **Additive fields.** `v1` surfaces new public fields, for example `reasonText` (suppression), `dnsProvider` (domain), and `autoWarmupEnabled` (IP). > [!NOTE] > > The request body format is unchanged. Versioning applies to **response** shapes only. The schemas shown on each endpoint page in this API Reference are the **`v1`** contract. Use them as the source of truth for the exact response of every endpoint under `v1`. For the complete field-by-field diff of every resource — added, renamed, and removed fields — see the [Changelog](/api-reference/changelog). ## How to migrate **1. Opt in on a test integration** Add `X-SendPost-Public-Contract: v1` to your requests in a staging or test environment and inspect the responses. ```bash theme={null} curl https://api.sendpost.io/api/v1/subaccount/suppression \ -H "X-SubAccount-ApiKey: YOUR_API_KEY" \ -H "X-SendPost-Public-Contract: v1" ``` **2. Update field names and parsing** Adjust for the camelCase renames (e.g. `publicIP` → `publicIp`, `messageID` → `messageId`) and remove any code that depended on internal fields `v1` no longer returns. The [Changelog](/api-reference/changelog) lists every change per resource. **3. Verify against the API Reference** Confirm your parsing matches the `v1` schemas documented on each endpoint page. **4. Pin v1 in production** Send `X-SendPost-Public-Contract: v1` on all production requests, and watch the `Deprecation` / `Sunset` headers to track the timeline. ## Questions Reach us at [dev@sendpost.io](mailto:dev@sendpost.io) if you need help planning your migration. # Changelog Source: https://docs.sendpost.io/api-reference/changelog Notable changes to the SendPost public REST API, including the full field-level diff of the v1 response contract. **2026-11-05** ## Webhook signing documentation corrected [Webhook Signature Verification](/api-reference/webhook/webhook-signature-verification) said webhooks are signed with your Account API Key. They are not: since May 2026 a webhook request is signed only when the webhook has its own secret, and a webhook without one is delivered without `X-SendPost-Signature`. * Set a secret with `secret` on [Create Webhook](/api-reference/webhook/create-a-new-webhook) or [Update Webhook](/api-reference/webhook/update-an-existing-webhook), or in the dashboard when you create the webhook. Then verify with that secret wherever you used the API key; the verification code is otherwise unchanged. * `secret` is now listed in the webhook request schema. The API already accepted it. * A per-email `webhookEndpoint` receives the email's events in addition to your account webhooks, not instead of them. Requests to it are signed only when its URL exactly matches an account webhook that has a secret. See [Per-Email Webhook Endpoints](/api-reference/webhook/webhook-signature-verification#per-email-webhook-endpoints). No API behavior changed with this update. **2026-10-22** ## Webhook create and update fixes * [Create Webhook](/api-reference/webhook/create-a-new-webhook) no longer fails with an empty HTTP 500 when the body has no `eventSubOptions`. * Fields you leave out on create now take their documented defaults: `enabled` and most events are on. Send `false` for anything you don't want. The SDKs already sent these defaults, so SDK integrations are unaffected. * [Update Webhook](/api-reference/webhook/update-an-existing-webhook) now changes only the fields you send. Before, every field you left out was switched off and the URL was cleared. * `url` must be an absolute `http://` or `https://` URL. Anything else returns HTTP 422 with `{"error": ""}`, and the other webhook errors now carry the same body. * The sub-account `apiKey` is returned only when you create a sub-account or regenerate its key. Listing or getting sub-accounts doesn't include it. Integrations that send every field get the same result as before. **2026-10-19** ## Real-time validation results on webhooks Sub-accounts with the Real-Time List Cleaning add-on can now receive the result of each email's address check as a **Validation** webhook event (type `82`). See [Real-Time Validation Results](/api-reference/webhook/validation-results). * `event.validationStatus` is `valid`, `invalid`, `catch all` or `unknown`. `invalid` emails are not sent. * Turn it on with `validated: true` on an account webhook, or the Validation checkbox in the dashboard. Filter results with `eventSubOptions.validated`. * Skip the check for one email with `skipValidation: true` on [Send Email](/api-reference/email/send-email) and [Send Email With Template](/api-reference/email/send-email-with-template), or the header `X-Sendpost-Validate: false`. * The webhook event type list now shows SMTP Dropped as `26`, its real value (it was listed as `10`). Existing integrations are unaffected: webhooks without `validated` receive the same events as before, and `validated` only appears in webhook responses when it is on. **2026-10-09** ## `tpspFrom` sender for third-party providers [Send Email](/api-reference/email/send-email) and [Send Email With Template](/api-reference/email/send-email-with-template) accept an optional `tpspFrom` sender. Emails delivered through a third-party sending provider (SendGrid, Amazon SES, Mailgun, SparkPost, Postmark or Custom SMTP) go out as `tpspFrom`; emails delivered on SendPost IPs still go out as `from`. * `tpspFrom` must be on the same registered domain as `from`, and must be set up as a sender at the provider. * Stats and webhook events stay under `from`. * An invalid `tpspFrom` rejects the request with HTTP 400 and `errorCode` 11. Existing integrations are unaffected: without `tpspFrom`, sending works exactly as before. **2026-09-22** ## Versioned response contract (legacy → v1) The public REST API now supports two response contracts, selected per request with the `X-SendPost-Public-Contract` header. * **`legacy`** (today's shape) remains the **default** — existing integrations are unaffected. * **`v1`** is available now via `X-SendPost-Public-Contract: v1`. * Responses carry `Deprecation`, `Sunset` (**31 March 2027, 23:59:59 UTC**), and `Link` headers. After the sunset, `v1` becomes the default. See [API Versioning & Migration](/api-reference/api-versioning) for the mechanism and step-by-step migration. ### What v1 changes, field by field `v1` normalizes field casing, removes internal/sensitive fields, and adds a few new fields. The complete diff per resource: > [accordion] Suppression > > * **Added:** `reasonText` — public reason label (`manual` / `unsubscribe` / `hardBounce` / `spamComplaint` / `unknown`). > * **Removed:** `groups`, `ipId`, `accountIPPoolId` (plus dashboard-only `ipPublicIP`, `ipPoolName`). > * **Note:** `smtpError` is **unchanged** (already camelCase in legacy — it is *not* renamed). > [accordion] IP > > * **Added:** `autoWarmupEnabled` (boolean; computed from warmup state). > * **Renamed:** `publicIP` → `publicIp`, `reverseDNSHostname` → `reverseDnsHostname`. > * **Removed:** `systemDomain`, `accountIPPools`, `autoWarmupPlan` (replaced by `autoWarmupEnabled`), `deliverabilityPolicies`, and all per-provider settings blobs (`gmailSettings` … `checkpointSettings`). > [accordion] IP Pool > > * **Sub-account pools:** add `shouldOverflow`, `overflowPoolName`. No removals. > * **Account pools:** **removed** `thirdPartySendingProviders`, `toAccountIPPools`, `warmupInterval`, `warmupIntervalSeconds`, `warmupQueueMode`, `resolveTemplateLocally`. > * Nested `ips[]` follow the **IP** changes above. > [accordion] Domain > > * **Added:** `dnsProvider` (detected DNS host). > * **Removed:** `gpt`, `gptVerified`, `dkimDelegationInfo`, `dmarcDelegationInfo`, `returnPathDelegationInfo`, `trackDelegationInfo`. > * **Unchanged under v1:** the `domain/v2` endpoints (`/subaccount/domain/v2`, `/account/domain/v2`) return the same shape for legacy and v1. > [accordion] Message > > * **Renamed:** `messageID` → `messageId`, `subAccountID` → `subAccountId`, `publicIP` → `publicIp`. > * **Removed:** `customFields`, `resolveTemplateLocally` (plus internal-plumbing fields already hidden from legacy). > [accordion] Event > > * **Renamed:** `eventID` → `eventId`, `messageID` → `messageId`, `messageSubject` → `subject`. > * **Removed (top-level):** `smtpCode`, `smtpDescription` (still available nested under `eventMetadata`), plus mock-send flags. > * **`eventMetadata`:** renamed `clickedURL` → `clickedUrl`, `trackedIP` → `trackedIp`, `cityID` → `cityId`; removed `sendpostLinkId` and all provider-specific fields (`sendgrid*`, `ses*`, `sparkpost*`, `mailgun*`, `customSmtp*`, `postmark*`). > [accordion] SubAccount > > * **Removed:** `smtpAuths`, `blocked_at`, `hb_exempt`, `generate_weekly_report`, `skip_global_suppression_check`, `handlers` (plus `block_reason`, `created_by`, `updated_by` already hidden from legacy). > * `apiKey`, `accountId` are unchanged. > [accordion] Member > > * **Renamed:** `url` → `logoUrl`. > * **Removed:** `isForbidden`, `notesColor`, `twoFactorEnabled`, `twoFactorVerifiedAt` (plus `firebaseUID`, `isGodMode` already hidden from legacy). > [accordion] Webhook > > * **Removed:** `secret` (HMAC signing key), `eventSubOptions`. `secret` remains available on the **legacy** contract for same-account callers. > * **List variant** (`successRate`): `v1` always returns a number; legacy returns `null` when unmeasured. > [accordion] Account / Account Setting > > * **Renamed:** `logoURL` → `logoUrl`. > * **Removed:** all billing internals (`stripe*`, `creditBalance`, `promoCode`, `isLegacyBilling`, `trialPeriod`, …), moderation/ops fields (`demoLocked*`, `*SlackEndpoint`, `slackToken`, `rbacEnabled`, `hubspotCompanyId`, …) and audit fields. Public callers already receive the curated `v1` shape today. > [accordion] Email (send) > > * **`EmailResponse`:** no field changes (`to`, `submittedAt`, `messageId`, `errorCode`, `message`). > * **Request body:** the TPSP routing internals `tpspIppool`, `tpspTemplate`, `tpspIp` are not part of the v1 shape. > [accordion] Stats (all stat endpoints) > > Pervasive v1 changes across the stat family: > > * **Removed everywhere:** the bot/human breakdown `botOpened`, `botClicked`, `humanOpened`, `humanClicked`; the ops-only `spamRate`, `totalQD`, `warmupVersion`, `warmupSkipped`; and the raw `day` / `month` / `year` date columns. > * **Renamed:** `publicIP` → `publicIp`, `ipid` → `ipId`; provider stats `email_type` → `emailType` (and `email_type`/`name` → `provider` on the provider breakdown); sub-account stats `sid` → `subAccountId`, `name` → `subAccountName`; account IP-pool stats `accountIPPoolId` → `ipPoolId`, `name` → `ipPoolName`. > * **`seedContactStats`** nested keys renamed: `rStat` → `rStats`, `agStat` → `groupStats`, `agDomainStat` → `domainStats`, `aIPStat` → `ipStats`, `aPStat` → `providerStats`. > * **`blacklistResource`** normalized from `Snake_Case`/`PascalCase` to camelCase throughout (`Add_Date` → `addDate`, `Last_Check` → `lastCheck`, `Contact_List_ID` → `contactListId`, etc.). > * **`?filter=bot`** returns a normalized `{ enabled, raw, filtered, botOpened, botClicked }` view under v1. > * **Unchanged:** `dateStat`, `validationStat`, `accountCycleUsage`, `postmasterDomainStat`. > [!NOTE] > > For the authoritative response of any endpoint under `v1`, the schema on that endpoint's API Reference page is the source of truth. # Unsubscribe Links Source: https://docs.sendpost.io/api-reference/common-use-cases/adding-unsubscribe-links Add unsubscribe links to emails using the built-in {{unsubscribe}} template variable. Recipients who click the link are automatically added to your suppression list. ```json theme={null} { "from": { "email": "marketing@example.com", "name": "Marketing Team" }, "to": [ { "email": "user@example.com", "name": "John Doe", "customFields": { "firstName": "John" } } ], "subject": "Special Offer Just for You!", "htmlBody": "

Hi {{firstName}},

We have an exclusive offer for you!

Unsubscribe from these emails

", "textBody": "Hi {{firstName}},\n\nWe have an exclusive offer for you!\n\nUnsubscribe from these emails: {{unsubscribe}}", "trackOpens": true, "trackClicks": true, "groups": [ "promotional" ] } ``` ## How It Works Use the `{{unsubscribe}}` template variable in your email body. SendPost replaces it with a unique unsubscribe URL for each recipient. Include it in both `htmlBody` and `textBody`. When a recipient clicks the unsubscribe link: * They're added to your account's suppression list * Future emails to that recipient are automatically dropped * You receive an `unsubscribed` webhook event (if webhooks are configured) ## Examples **HTML email:** ```html theme={null}

Don't want to receive these emails? Click here to unsubscribe

``` **Plain text email:** ``` Don't want to receive these emails? Unsubscribe here: {{unsubscribe}} ``` **Styled unsubscribe link:** ```html theme={null}

Unsubscribe

``` > [!WARNING] > > `unsubscribe` is a reserved custom field name. You cannot use it as a custom field name in your `customFields` object. > [!NOTE] > > The unsubscribe link is unique for each recipient and email. Once a recipient clicks the unsubscribe link, they are immediately added to your suppression list, and you will receive an `unsubscribed` webhook event (if webhooks are configured). # Managing Senders Source: https://docs.sendpost.io/api-reference/common-use-cases/controlling-sender-name-and-email Set the sender name and email address that appears in recipient inboxes using the from field. ```json theme={null} { "from": { "email": "support@example.com", "name": "Support Team" }, "to": [ { "email": "customer@example.com", "name": "John Doe" } ], "subject": "Welcome to Our Service!", "htmlBody": "

Hi John,

Welcome aboard!

", "textBody": "Hi John,\n\nWelcome aboard!", "trackOpens": true, "trackClicks": true } ``` ## Sender Email and Name Use the `from` object to control the sender identity that recipients see in their inbox. * `from.email` (required): The email address. Must use a verified domain in your SendPost account. * `from.name` (optional): The display name shown in email clients. When both fields are provided, recipients see `"Display Name" `. If only `from.email` is provided, recipients see the email address only. ## Common Use Cases ### Support Emails ```json theme={null} { "from": { "email": "support@example.com", "name": "Support Team" } } ``` Recipients see: `Support Team ` ### Marketing Emails ```json theme={null} { "from": { "email": "marketing@example.com", "name": "Marketing" } } ``` Recipients see: `Marketing ` ### Product-Specific Emails ```json theme={null} { "from": { "email": "notifications@example.com", "name": "Product Updates" } } ``` Recipients see: `Product Updates ` ### Personal-Style Emails ```json theme={null} { "from": { "email": "sarah@example.com", "name": "Sarah from Example" } } ``` Recipients see: `Sarah from Example ` ### Company Branding ```json theme={null} { "from": { "email": "hello@example.com", "name": "Example Company" } } ``` Recipients see: `Example Company ` ## Examples ### Order Confirmation (Transactional) ```json theme={null} { "from": { "email": "orders@example.com", "name": "Order Confirmation" }, "subject": "Your order has been confirmed" } ``` ### Newsletter (Promotional) ```json theme={null} { "from": { "email": "newsletter@example.com", "name": "Example Newsletter" }, "subject": "Monthly Newsletter - July 2024" } ``` ### Password Reset (Security) ```json theme={null} { "from": { "email": "security@example.com", "name": "Security Team" }, "subject": "Password Reset Request" } ``` ## Best Practices * Use clear, recognizable sender names that match the email type. * Maintain consistent sender names across similar email types to build recognition. * Avoid generic names like "noreply" which may reduce engagement. > [!WARNING] > > The email address in `from.email` must belong to a domain verified in your SendPost account. Sending from an unverified domain returns an error. > [!NOTE] > > Webhook payloads include the sender name and email, so you can track which sender identity was used for each email event. # Custom Headers Source: https://docs.sendpost.io/api-reference/common-use-cases/custom-headers Pass custom key-value pairs in email requests to track campaigns, customers, and events. Headers are included in all webhook events for easy reconciliation. ```json theme={null} { "from": { "email": "support@example.com", "name": "Support Team" }, "to": [ { "email": "customer@example.com", "name": "John Doe" } ], "subject": "Order Confirmation", "htmlBody": "

Thank you for your order!

", "headers": { "Contact-ID": "12345", "Campaign-ID": "summer-sale-2024", "Customer-ID": "CUST-789", "Account-ID": "ACC-456" }, "trackOpens": true, "trackClicks": true, "ippool": "marketing" } ``` ## How It Works Include a `headers` object in your email request with any custom key-value pairs. These headers are preserved throughout the email lifecycle and included in all webhook event payloads. When an email is processed, delivered, hard bounced, soft bounced, opened, clicked, unsubscribed, or marked as spam, the webhook event includes your custom headers in the `emailMessage.headers` object. This makes it easy to reconcile events, update statistics for your customers, or create custom internal dashboards. ## Use Cases ### SaaS Companies Track which customer account triggered each email: ```json theme={null} { "headers": { "Account-ID": "acc_123456", "User-ID": "user_789", "Plan-Type": "enterprise" } } ``` ### Email Marketing Agencies Identify campaigns and clients: ```json theme={null} { "headers": { "Client-ID": "client_abc", "Campaign-ID": "campaign_xyz", "Campaign-Type": "newsletter" } } ``` ### Email Marketing Platforms Link emails to contacts and campaigns: ```json theme={null} { "headers": { "Contact-ID": "contact_123", "Campaign-ID": "campaign_456", "List-ID": "list_789" } } ``` ## Headers in Webhook Events Custom headers are included in all webhook event types: * **Processed** (type: 0) * **Dropped** (type: 1) * **Delivered** (type: 2) * **SoftBounced** (type: 3) * **HardBounced** (type: 4) * **Opened** (type: 5) * **Clicked** (type: 6) * **Unsubscribed** (type: 7) * **Spam** (type: 8) ### Example: Webhook Payload with Custom Headers ```json theme={null} { "event": { "eventID": "edhg-123gh-afasdf-124egh", "type": 5, "messageID": "mjhl-1401-sasdf-129324", "eventMetadata": { "userAgent": { "Family": "Chrome", "Major": "91" } } }, "emailMessage": { "messageID": "mjhl-1401-sasdf-129324", "from": { "email": "support@example.com", "name": "Support Team" }, "to": [ { "email": "customer@example.com", "name": "John Doe" } ], "subject": "Order Confirmation", "headers": { "Contact-ID": "12345", "Campaign-ID": "summer-sale-2024", "Customer-ID": "CUST-789", "Account-ID": "ACC-456" } } } ``` ## Examples ### Transactional Email with Order Tracking ```json theme={null} { "from": { "email": "orders@example.com", "name": "Order Confirmation" }, "to": [ { "email": "customer@example.com" } ], "subject": "Your order has been confirmed", "htmlBody": "

Thank you for your order!

", "headers": { "Order-ID": "ORD-12345", "Customer-ID": "CUST-789", "Transaction-ID": "TXN-456" } } ``` ### Marketing Campaign with Segmentation ```json theme={null} { "from": { "email": "marketing@example.com", "name": "Marketing Team" }, "to": [ { "email": "user@example.com" } ], "subject": "Special Offer Just for You!", "htmlBody": "

Check out our latest offer!

", "headers": { "Campaign-ID": "summer-sale-2024", "Segment-ID": "vip-customers", "Agency-Client-ID": "client_abc" } } ``` ### Multi-Tenant Application ```json theme={null} { "from": { "email": "notifications@example.com", "name": "Notifications" }, "to": [ { "email": "user@example.com" } ], "subject": "Welcome to Our Platform", "htmlBody": "

Welcome aboard!

", "headers": { "Tenant-ID": "tenant_123", "User-ID": "user_456", "Workspace-ID": "workspace_789" } } ``` ### Skipping Real-Time Validation for One Email If your sub-account has the Real-Time List Cleaning add-on, add the header `X-Sendpost-Validate: false` to send an email without checking the address first. It works the same as `skipValidation: true` and also works over SMTP relay. See [Real-Time Validation Results](/api-reference/webhook/validation-results). ```json theme={null} { "from": { "email": "notifications@example.com" }, "to": [ { "email": "known.good@example.com" } ], "subject": "Your receipt", "htmlBody": "

Thanks for your order.

", "headers": { "X-Sendpost-Validate": "false" } } ``` > [!NOTE] > > Custom headers are preserved exactly as you send them. Use consistent naming conventions (e.g., `Contact-ID`, `Campaign-ID`) across your application to make webhook processing easier. > [!NOTE] > > Headers are included in every webhook event for a given email, allowing you to filter and process webhooks based on your custom identifiers without needing to store additional mapping data. # Multi-Tenant Applications Source: https://docs.sendpost.io/api-reference/common-use-cases/multi-tenant Build multi-tenant email applications by creating sub-accounts for each tenant, managing domains and IPPools, and using custom headers for event reconciliation via webhooks. Multi-tenant applications require isolating email sending infrastructure, tracking, and analytics per tenant. SendPost provides sub-accounts, domain management, IPPool routing, and custom headers to build scalable multi-tenant email systems. ## Architecture Overview A multi-tenant email application typically requires: 1. **Sub-account isolation**: Create a separate sub-account for each tenant 2. **Domain management**: Whitelist and verify sending domains per sub-account 3. **Custom headers**: Include tenant identifiers in email requests for webhook reconciliation 4. **IPPool routing**: Use shared IPPools for smaller tenants and dedicated IPPools for high-volume senders 5. **Webhook processing**: Consume webhook events with custom headers to reconcile stats per tenant ## Creating Sub-Accounts for Tenants Create a new sub-account for each tenant when they sign up or when you need to isolate their email sending. ```json theme={null} POST /api/v1/account/subaccount/ X-Account-ApiKey: your_account_api_key { "name": "tenant-acme-corp", "companyName": "Acme Corporation" } ``` Each sub-account receives its own API key (`X-SubAccount-ApiKey`) for sending emails and managing sub-account resources. Store the sub-account ID and API key in your tenant database. > [!NOTE] > > Use the Account API key (`X-Account-ApiKey`) to create and manage sub-accounts. Use the Sub-Account API key (`X-SubAccount-ApiKey`) for all email sending and sub-account-specific operations. ## Managing Domains Per Sub-Account After creating a sub-account, create and verify sending domains for that tenant. Each sub-account can have multiple verified domains. ### Creating a Domain ```json theme={null} POST /api/v1/subaccount/domain X-SubAccount-ApiKey: tenant_subaccount_api_key { "domain": "mail.acme-corp.com" } ``` ### Verifying Domain Ownership After creating a domain, SendPost provides DNS records (SPF, DKIM, DMARC) that must be added to your tenant's DNS. Retrieve the domain details to get the required DNS records: ```json theme={null} GET /api/v1/subaccount/domain/{domain_id} X-SubAccount-ApiKey: tenant_subaccount_api_key ``` Once DNS records are verified, the domain is ready for sending. Use the verified domain in the `from.email` field when sending emails for that tenant. > [!NOTE] > > Domain verification is required before sending emails. Unverified domains will cause email sending to fail. See [Create a New Domain](/api-reference/domain/create-a-new-domain) for detailed DNS configuration steps. ## Using Custom Headers for Tenant Identification Include custom headers in every email request to identify the tenant and enable webhook reconciliation. Headers are preserved throughout the email lifecycle and included in all webhook events. ```json theme={null} { "from": { "email": "notifications@mail.acme-corp.com", "name": "Acme Corp" }, "to": [ { "email": "user@example.com", "name": "John Doe" } ], "subject": "Welcome to Acme Corp", "htmlBody": "

Welcome aboard!

", "headers": { "Tenant-ID": "acme-corp-123", "Workspace-ID": "workspace-456", "User-ID": "user-789" }, "trackOpens": true, "trackClicks": true, "ippool": "shared-marketing" } ``` ### Header Best Practices * Use consistent naming conventions (e.g., `Tenant-ID`, `Workspace-ID`) * Include tenant identifiers in every email request * Store header values in your tenant database for easy lookup * Use headers to filter webhook events in your application > [!NOTE] > > Custom headers are included in all webhook events (Processed, Delivered, Opened, Clicked, Bounced, Unsubscribed, Spam), making it easy to reconcile events per tenant. See [Custom Headers](/api-reference/common-use-cases/custom-headers) for more details. ## Managing IPPools for Multi-Tenant Routing IPPools control which IP addresses or third-party sending providers (TPSPs) are used for sending emails. Use different IPPool strategies based on tenant volume and requirements. ### Shared IPPools for Smaller Tenants Smaller tenants should use shared IPPools that distribute sending across multiple IPs and TPSPs. This provides cost efficiency and adequate deliverability. ```json theme={null} { "from": { "email": "notifications@mail.acme-corp.com", "name": "Acme Corp" }, "to": [ { "email": "user@example.com" } ], "subject": "Welcome", "htmlBody": "

Welcome!

", "ippool": "shared-pool" } ``` ### Dedicated IPPools for High-Volume Tenants Large-volume tenants may require dedicated IPPools for better deliverability, reputation management, and compliance. Create dedicated IPPools and assign them to specific tenants. ```json theme={null} POST /api/v1/account/ippool X-Account-ApiKey: your_account_api_key { "name": "acme-corp-dedicated", "ips": ["IP_100", "IP_101"], "routingStrategy": 0, "routingMetaData": "{}" } ``` Then use the dedicated IPPool when sending emails for that tenant: ```json theme={null} { "from": { "email": "notifications@mail.acme-corp.com", "name": "Acme Corp" }, "to": [ { "email": "user@example.com" } ], "subject": "Welcome", "htmlBody": "

Welcome!

", "ippool": "acme-corp-dedicated" } ``` ### IPPool Routing Strategies SendPost supports multiple routing strategies for IPPools: * **Round Robin (0)**: Distribute emails evenly across all IPs and TPSPs * **Email Provider Strategy (1)**: Route emails based on recipient email provider (Gmail, Yahoo, Microsoft, etc.) * **Volume Percentage Strategy (2)**: Assign specific volume percentages to each IP or TPSP * **Sending Domain Strategy (3)**: Route emails based on the sending domain See [IPPool Routing](/api-reference/ippools/routing) for detailed routing strategy configuration. > [!NOTE] > > IPPools are managed at the account level using `X-Account-ApiKey`, but can be used by any sub-account when sending emails. Assign IPPool names to tenants in your database to control which pool each tenant uses. ## Webhook Reconciliation When an email is processed, delivered, hard bounced, soft bounced, opened, clicked, unsubscribed, or marked as spam, SendPost sends a webhook event to your configured endpoint. The webhook payload includes your custom headers, allowing you to reconcile events per tenant. ### Webhook Event Structure ```json theme={null} { "event": { "eventID": "edhg-123gh-afasdf-124egh", "type": 5, "messageID": "mjhl-1401-sasdf-129324", "eventMetadata": { "userAgent": { "Family": "Chrome", "Major": "91" } } }, "emailMessage": { "messageID": "mjhl-1401-sasdf-129324", "from": { "email": "notifications@mail.acme-corp.com", "name": "Acme Corp" }, "to": [ { "email": "user@example.com", "name": "John Doe" } ], "subject": "Welcome to Acme Corp", "headers": { "Tenant-ID": "acme-corp-123", "Workspace-ID": "workspace-456", "User-ID": "user-789" }, "groups": ["transactional", "welcome"] } } ``` ### Processing Webhooks 1. **Extract tenant identifier**: Read `emailMessage.headers.Tenant-ID` from the webhook payload 2. **Identify event type**: Check `event.type` to determine the event (Delivered, Opened, Clicked, etc.) 3. **Update tenant stats**: Update your tenant's statistics based on the event type 4. **Store event data**: Persist the event in your database for analytics and reporting ### Webhook Event Types | Event Type | Type Value | Description | | - | - | - | | Processed | 0 | Email accepted and queued for sending | | Dropped | 1 | Email dropped before delivery (invalid address or in suppression list) | | Delivered | 2 | Email successfully delivered to recipient's mail server | | SoftBounced | 3 | Temporary delivery failure (will retry) | | HardBounced | 4 | Permanent delivery failure (invalid address) | | Opened | 5 | Recipient opened the email | | Clicked | 6 | Recipient clicked a link in the email | | Unsubscribed | 7 | Recipient clicked unsubscribe link | | Spam | 8 | Recipient marked email as spam | > [!NOTE] > > Custom headers are included in every webhook event for a given email, allowing you to filter and process webhooks based on tenant identifiers without needing to store additional mapping data. See [Understanding Webhook Event Lifecycle](/api-reference/webhook/understanding-webhook-event-lifecycle) for complete event lifecycle details. ## Complete Multi-Tenant Example Here's a complete example of setting up and sending emails for a new tenant: ### 1. Create Sub-Account ```json theme={null} POST /api/v1/account/subaccount/ X-Account-ApiKey: your_account_api_key { "name": "tenant-acme-corp", "companyName": "Acme Corporation" } ``` Response: ```json theme={null} { "id": 12345, "name": "tenant-acme-corp", "companyName": "Acme Corporation", "apiKey": "AHEZEP8192SEGH" } ``` ### 2. Create and Verify Domain ```json theme={null} POST /api/v1/subaccount/domain X-SubAccount-ApiKey: AHEZEP8192SEGH { "domain": "mail.acme-corp.com" } ``` Add DNS records to tenant's DNS, then verify domain is ready for sending. ### 3. Send Email with Custom Headers ```json theme={null} POST /api/v1/subaccount/email/ X-SubAccount-ApiKey: AHEZEP8192SEGH { "from": { "email": "notifications@mail.acme-corp.com", "name": "Acme Corp" }, "to": [ { "email": "user@example.com", "name": "John Doe", "customFields": { "firstName": "John" } } ], "subject": "Welcome {{firstName}}!", "htmlBody": "

Hi {{firstName}}, welcome to Acme Corp!

Unsubscribe

", "headers": { "Tenant-ID": "acme-corp-123", "Workspace-ID": "workspace-456" }, "ippool": "shared-pool", "trackOpens": true, "trackClicks": true, "groups": ["transactional", "welcome"] } ``` ### 4. Process Webhook Events When the email is delivered, opened, or clicked, you'll receive webhook events with the custom headers: ```json theme={null} { "event": { "type": 5, "messageID": "mjhl-1401-sasdf-129324" }, "emailMessage": { "headers": { "Tenant-ID": "acme-corp-123", "Workspace-ID": "workspace-456" } } } ``` Extract `Tenant-ID` from headers and update tenant statistics accordingly. ## Related Use Cases Multi-tenant applications also leverage these features: * **[Personalization](/api-reference/common-use-cases/personalisation-within-emails)**: Use Handlebars templating with `customFields` to personalize email content per recipient * **[Unsubscribe Links](/api-reference/common-use-cases/adding-unsubscribe-links)**: Add `{{unsubscribe}}` template variables to comply with email regulations * **[Sender Name and Email Control](/api-reference/common-use-cases/controlling-sender-name-and-email)**: Set tenant-specific sender identities using the `from` field * **[Email Classification](/api-reference/common-use-cases/using-groups-for-email-classification)**: Use `groups` to categorize emails by type, campaign, or product line for analytics ## Best Practices 1. **Isolate by sub-account**: Create separate sub-accounts for each tenant to ensure complete isolation 2. **Verify domains early**: Set up and verify domains as part of tenant onboarding 3. **Always include headers**: Include tenant identifiers in every email request for webhook reconciliation 4. **Choose appropriate IPPools**: Use shared IPPools for smaller tenants and dedicated IPPools for high-volume senders 5. **Process webhooks idempotently**: Use `eventID` to prevent duplicate processing of webhook events 6. **Monitor tenant stats**: Use custom headers to filter and aggregate statistics per tenant from webhook events > [!WARNING] > > Each sub-account requires its own verified domain. Sending from unverified domains will fail. Ensure domains are verified before sending emails for a tenant. > [!NOTE] > > Sub-accounts provide complete isolation: each tenant has separate API keys, domains, suppressions, and statistics. Use sub-accounts to ensure tenant data and sending infrastructure remain isolated. # Personalize Emails Source: https://docs.sendpost.io/api-reference/common-use-cases/personalisation-within-emails Use Handlebars templating to personalize email content in the subject, HTML body, and text body with custom field variables. ```json theme={null} { "from": { "email": "richard@piedpiper.com", "name": "Richard" }, "to": [ { "email": "gavin@hooli.com", "name": "Gavin Belson", "customFields": { "firstName": "Gavin", "discountCode": "BELSON240", "status": "VIP" } }, { "email": "erlich@piedpiper.com", "name": "Erlich Bachman", "customFields": { "firstName": "Erlich", "discountCode": "BACHMAN10", "status": "Incubator" } }, ], "subject": "Hello, {{firstName}}! Welcome to Pied Piper!", "htmlBody": "

Hi {{firstName}},

Your discount code is {{discountCode}}. Your account status is {{status}}.

", "textBody": "Hi {{firstName}},\n\nYour discount code is {{discountCode}}. Your account status is {{status}}.", "ippool": "default", "trackOpens": true, "trackClicks": true, "groups": [ "special-offers" ] } ``` ### How It Works Add a `customFields` object to each recipient in the `to` array. Use Handlebars syntax (`{{variableName}}`) in your subject, `htmlBody`, and `textBody` to reference these fields. SendPost replaces the placeholders with values from each recipient's `customFields` object. ### Output **[gavin@hooli.com](mailto:gavin@hooli.com):** * Subject: Hello, Gavin! Welcome to Pied Piper! * Body: Hi Gavin, Your discount code is **BELSON240**. Your account status is VIP. **[erlich@piedpiper.com](mailto:erlich@piedpiper.com):** * Subject: Hello, Erlich! Welcome to Pied Piper! * Body: Hi Erlich, Your discount code is **BACHMAN10**. Your account status is Incubator. ## Advanced Personalization ### Nested Fields Access nested properties in `customFields` using dot notation. **Example:** ```json theme={null} { "from": { "email": "noreply@sendpost.io", "name": "SendPost Team" }, "to": [ { "email": "john@example.com", "name": "John Doe", "customFields": { "user": { "firstName": "John", "lastName": "Doe", "address": { "city": "San Francisco", "state": "CA" } } } } ], "subject": "Welcome {{user.firstName}}!", "htmlBody": "

Hello {{user.firstName}} {{user.lastName}}!

We see you're located in {{user.address.city}}, {{user.address.state}}.

", "textBody": "Hello {{user.firstName}} {{user.lastName}}!\n\nWe see you're located in {{user.address.city}}, {{user.address.state}}." } ``` **Output:** * Subject: Welcome John! * HTML: Hello John Doe! We see you're located in San Francisco, CA. ### Array Iteration Iterate over arrays in `customFields` using the `{{#each}}` helper. **Example:** ```json theme={null} { "to": [ { "email": "alice@example.com", "name": "Alice Johnson", "customFields": { "firstName": "Alice", "orders": [ { "id": "ORD-001", "product": "Premium Plan", "amount": 99.99 }, { "id": "ORD-002", "product": "Add-on Storage", "amount": 29.99 } ] } } ], "subject": "{{firstName}}, Your Order History", "htmlBody": "

Your Recent Orders

    {{#each orders}}
  • {{id}}: {{product}} - ${{amount}}
  • {{/each}}
", "textBody": "Your Recent Orders:\n\n{{#each orders}}{{id}}: {{product}} - ${{amount}}\n{{/each}}" } ``` **Output:** * Subject: Alice, Your Order History * HTML: * ORD-001: Premium Plan - \$99.99 * ORD-002: Add-on Storage - \$29.99 ### Nested Objects With Arrays Combine nested objects and arrays for complex data structures. **Example:** ```json theme={null} { "to": [ { "email": "bob@example.com", "name": "Bob Wilson", "customFields": { "order": { "id": "ORD-12345", "customer": { "firstName": "Bob", "shipping": { "address": { "city": "New York", "state": "NY" } } }, "items": [ { "name": "Product A", "price": 79.99, "quantity": 1 }, { "name": "Product B", "price": 29.99, "quantity": 2 } ], "total": 139.97 } } } ], "subject": "Order {{order.id}} Confirmed - Thank You {{order.customer.firstName}}!", "htmlBody": "

Order Confirmation

Hi {{order.customer.firstName}},

Your order {{order.id}} has been confirmed.

Items:

    {{#each order.items}}
  • {{name}} - ${{price}} (Qty: {{quantity}})
  • {{/each}}

Shipping to: {{order.customer.shipping.address.city}}, {{order.customer.shipping.address.state}}

Total: ${{order.total}}

", "textBody": "Order Confirmation\n\nHi {{order.customer.firstName}},\n\nYour order {{order.id}} has been confirmed.\n\nItems:\n{{#each order.items}}{{name}} - ${{price}} (Qty: {{quantity}})\n{{/each}}\nShipping to: {{order.customer.shipping.address.city}}, {{order.customer.shipping.address.state}}\n\nTotal: ${{order.total}}" } ``` **Output:** * Subject: Order ORD-12345 Confirmed - Thank You Bob! * HTML: Order confirmation with customer info, items list, shipping address, and total ## Syntax Reference ### Basic Syntax * Variables: `{{variableName}}` * Nested properties: `{{object.property}}` or `{{object.nested.property}}` * Array iteration: `{{#each arrayName}}...{{/each}}` * Current item: `{{this}}` (inside `{{#each}}`) * Array index: `{{@index}}` (0-based, inside `{{#each}}`) * Conditionals: `{{#if condition}}...{{/if}}` or `{{#if condition}}...{{else}}...{{/if}}` ### Common Patterns **Iterate over array:** ``` {{#each items}}
  • {{this}}
  • {{/each}} ``` **Iterate over array of objects:** ``` {{#each orders}}

    {{id}}: {{product}} - ${{amount}}

    {{/each}} ``` **Check if array has items:** ``` {{#if items}} {{#each items}}
  • {{this}}
  • {{/each}} {{else}}

    No items found.

    {{/if}} ``` **Nested iteration:** ``` {{#each categories}}

    {{name}}

      {{#each products}}
    • {{this}}
    • {{/each}}
    {{/each}} ``` ## Important Notes > [!WARNING] > > `unsubscribe` is a reserved custom field name. You can't use it as a custom field name. 1. **Case sensitivity:** Field names are case-sensitive. `{{firstName}}` and `{{FirstName}}` are different. 2. **Empty arrays:** Empty arrays don't render anything in `{{#each}}` blocks. Use `{{#if}}` to check for empty arrays. 3. **Null/undefined values:** If a nested property doesn't exist, an empty string is rendered. Use `{{#if}}` to check for existence. 4. **Data structure:** Ensure your `customFields` structure matches your template expectations. Nested objects and arrays must be valid JSON. # Email Classification Source: https://docs.sendpost.io/api-reference/common-use-cases/using-groups-for-email-classification Categorize and tag emails with groups to organize, filter, and analyze performance. Separate transactional from promotional emails, track campaigns, or analyze by product line. ```json theme={null} { "from": { "email": "support@example.com", "name": "Support Team" }, "to": [ { "email": "customer@example.com", "name": "Jane Smith", "customFields": { "orderNumber": "ORD-12345" } } ], "subject": "Your Order #{{orderNumber}} has been shipped", "htmlBody": "

    Hi Jane,

    Your order has been shipped and is on its way!

    ", "textBody": "Hi Jane,\n\nYour order has been shipped and is on its way!", "trackOpens": true, "trackClicks": true, "groups": [ "transactional", "order-updates", "shipping-notifications" ] } ``` ## Overview Groups are optional string arrays that categorize emails. Assign multiple groups per email to organize by type, campaign, product line, or any classification. Use groups to filter and analyze performance via the Stats API. ## Features * **Multiple groups per email**: Assign an array of group names to a single email (e.g., `["transactional", "order-updates"]`). * **Flexible naming**: Use any string naming convention. * **Analytics filtering**: Filter stats and analyze performance by category. * **Optional**: Omit groups if not needed. ## Common Use Cases ### Separating Transactional and Promotional Emails ```json theme={null} { "groups": ["transactional"] } ``` or ```json theme={null} { "groups": ["promotional"] } ``` ### Tracking Campaigns ```json theme={null} { "groups": ["summer-sale-2024", "email-campaign"] } ``` ### Product Line Classification ```json theme={null} { "groups": ["product-electronics", "product-accessories"] } ``` ### Email Type Classification ```json theme={null} { "groups": ["welcome-series", "user-onboarding", "week-1"] } ``` ## Examples ### Transactional Email ```json theme={null} { "subject": "Order Confirmation", "groups": ["transactional", "order-confirmation"], "htmlBody": "

    Thank you for your order!

    " } ``` ### Promotional Email ```json theme={null} { "subject": "Special Offer - 50% Off!", "groups": ["promotional", "summer-sale"], "htmlBody": "

    Don't miss our summer sale!

    " } ``` ### Newsletter ```json theme={null} { "subject": "Monthly Newsletter - July 2024", "groups": ["newsletter", "monthly-updates"], "htmlBody": "

    Here's what's new this month...

    " } ``` ## Using Groups with the Stats API Filter and analyze performance by group using the [Get aggregated stats by group](/api-reference/stats/get-aggregated-stats-by-group) endpoint. Compare performance across email types, campaigns, or product lines. > [!NOTE] > > Groups are case-sensitive. Use consistent naming conventions (e.g., always lowercase or always kebab-case) to avoid duplicate groups. > [!NOTE] > > Groups are stored with each email message and included in webhook payloads. Filter webhook events by group in your application. # Create Domain Source: https://docs.sendpost.io/api-reference/domain/create-a-new-domain post /subaccount/domain Register a new sending domain with SendPost. After creation, you'll receive DNS records that must be configured with your DNS provider before you can send emails. **Domain Setup Process:** 1. Call this endpoint with your domain name 2. Copy the returned DNS records (DKIM, Return-Path, Track, DMARC) 3. Add records to your DNS provider (GoDaddy, Cloudflare, Route53, etc.) 4. Wait for DNS propagation (typically 15 minutes to 48 hours) 5. Verification happens automatically, or trigger manual verification **DNS Records Explained:** | Record | Purpose | Required | |--------|---------|----------| | DKIM | Cryptographically signs emails to prove authenticity | Yes | | Return-Path | Routes bounce notifications through SendPost | Recommended | | Track | Enables click tracking with your domain | Optional | | DMARC | Adds additional authentication layer | Recommended | **Best Practices:** - Use a subdomain like `mail.yourdomain.com` for sending - Keep your root domain for your website - Configure all records for best deliverability # Delete Domain Source: https://docs.sendpost.io/api-reference/domain/delete-a-specific-domain delete /subaccount/domain/{domain_id} Remove a sending domain from your sub-account. Once deleted, you can no longer send emails from addresses on this domain. **Before Deleting:** - Ensure no active email campaigns use this domain - Update sender addresses in your applications - Consider impact on email deliverability **Note:** DNS records for the domain will become orphaned. You may want to remove them from your DNS provider. # Get Domain Source: https://docs.sendpost.io/api-reference/domain/get-a-specific-domain get /subaccount/domain/{domain_id} Retrieve detailed information about a specific sending domain, including DNS record configuration and verification status. **Response includes:** - Domain name and ID - DKIM, Return-Path, Track, and DMARC DNS records to configure - Verification status for each record type - Failure reasons if verification failed - Domain registration date **Use Cases:** - Check verification status before sending emails - Retrieve DNS records during domain setup - Debug DNS configuration issues - Audit domain settings for compliance # List Domains Source: https://docs.sendpost.io/api-reference/domain/get-all-domains get /subaccount/domain Retrieve all sending domains configured for this sub-account. Use this endpoint to audit your domain setup, check verification status, or retrieve DNS records for configuration. **Each domain record includes:** - Domain name and unique ID - DNS records to configure (DKIM, Return-Path, Track, DMARC) - Verification status for each record type - Failure messages for troubleshooting - Creation timestamp **Verification Status Values:** - `true` - Record verified and active - `false` - Record not verified (check DNS configuration) **Use Cases:** - Audit all configured sending domains - Export DNS records for documentation - Identify domains pending verification - Monitor domain health across multiple domains **Pagination:** Use `limit` and `offset` for large domain lists. # Send Email Source: https://docs.sendpost.io/api-reference/email/send-email post /subaccount/email/ Send transactional or marketing emails to one or multiple recipients. This is the primary endpoint for all email sending through SendPost. **Capabilities:** - **Single Email**: Send to one recipient with full personalization - **Batch Sending**: Send to up to 500 recipients in a single API call - **Personalization**: Use Handlebars templating (`{{variableName}}`) in subject, HTML body, and text body - **Attachments**: Include base64-encoded files (max 25MB total per request) - **Tracking**: Enable/disable open and click tracking per email - **IP Pool Routing**: Route emails through specific IP pools **Common Use Cases:** | Use Case | Example | |----------|---------| | Order Confirmation | Send receipt with order details after purchase | | Password Reset | Time-sensitive security email with reset link | | Welcome Email | Onboard new users with personalized greeting | | Shipping Notification | Update customers when orders ship | | Invoice/Receipt | Attach PDF invoices to billing emails | **Personalization Example:** ```json { "to": [{ "email": "john@example.com", "customFields": { "firstName": "John", "orderTotal": "$99.99" } }], "subject": "Hi {{firstName}}, your order is confirmed!", "htmlBody": "

    Thanks {{firstName}}! Your total: {{orderTotal}}

    " } ``` **Test Email Addresses:** SendPost provides special test email addresses for testing webhooks and events without sending real emails: | Test Email | Behavior | |------------|----------| | `test@playwithsendpost.io` | Generates delivered event, then simulates opens and clicks after a few seconds | | `deliver@playwithsendpost.io` | Generates delivered event only (no opens/clicks) | | `hardbounce@playwithsendpost.io` | Always generates a hard bounce event | | `softbounce@playwithsendpost.io` | Always generates a soft bounce event | | `dropped@playwithsendpost.io` | Always generates a dropped event (SMTPDropped) | **Self-Test Email (Send to Yourself):** Use `hello@playwithsendpost.io` as the **from** address to send emails to yourself for testing: - **Sender**: Must be `hello@playwithsendpost.io` - **Recipient**: Must be your account owner email (the email you used to sign up) - **Behavior**: Real email delivery to your inbox (no domain verification required, no mock mode) - **Use Case**: Test your API integration by sending real emails to yourself without domain setup **Example:** ```json { "from": {"email": "hello@playwithsendpost.io"}, "to": [{"email": "your-account-email@example.com"}], "subject": "Test Email to Myself", "htmlBody": "

    This is a test email to myself

    " } ``` This will send a real email to your inbox that you can actually receive and open. **Note**: If you send to any email other than your account email, the request will be rejected with an error. **Using Test Emails:** - Simply send to any test email address like a normal recipient - Mock mode is automatically enabled for test emails - All events trigger webhooks normally - Events are marked as mock messages but follow the same structure as real events - Perfect for testing webhook integrations without using real email addresses **Example:** ```json { "to": [{"email": "test@playwithsendpost.io"}], "from": {"email": "sender@example.com"}, "subject": "Test Email", "htmlBody": "

    This is a test

    " } ``` This will generate: Sent → Delivered → Opened (after 2-5s) → Clicked (after 1-3s more) **Response:** Returns an array of responses, one per recipient, each containing: - `messageId` - Unique ID for tracking - `submittedAt` - Timestamp of acceptance - `errorCode` and `message` - Status information # Send Email With Template Source: https://docs.sendpost.io/api-reference/email/send-email-with-template post /subaccount/email/template Send emails using pre-configured templates stored in SendPost. Templates separate email content from code, enabling: **Benefits:** - Update email content without code deployments - Marketing teams can manage templates independently - Consistent branding across all applications - A/B test different template versions **How It Works:** 1. Create templates in the SendPost dashboard with Handlebars variables 2. Reference the template by name or ID in this API call 3. Pass dynamic data through recipient `customFields` 4. SendPost merges data with template and sends **Common Use Cases:** | Template Type | Dynamic Data | |---------------|--------------| | Welcome Email | `firstName`, `accountType`, `loginUrl` | | Order Receipt | `orderNumber`, `items`, `total`, `shippingAddress` | | Password Reset | `resetLink`, `expiryTime`, `userName` | | Weekly Digest | `articleList`, `unreadCount`, `userName` | **Example Request:** ```json { "from": { "email": "orders@yourstore.com" }, "to": [{ "email": "customer@example.com", "customFields": { "firstName": "Sarah", "orderNumber": "ORD-2024-001", "totalAmount": "$149.99" } }], "template": "order-confirmation-v2" } ``` **Note:** Template variables not provided in `customFields` will render as empty strings. # Introduction Source: https://docs.sendpost.io/api-reference/introduction Understand the basics of SendPost REST convention and common parameters SendPost API is built on REST API principles. Authenticated users can interact with any of the API endpoints to perform: * **GET**- to get a resource * **POST** - to create a resource * **PUT** - to update an existing resource * **DELETE** - to delete a resource The API endpoint for all API calls is: ``` https://api.sendpost.io/api/v1 ``` Some conventions that have been followed in the API design overall are following: * All resources have either `/api/v1/subaccount` or `/api/v1/account` in their API call resource path based on who is authorised for the resource. All API calls with path `/api/v1/subaccount` use `X-SubAccount-ApiKey` in their request header. Likewise all API calls with path `/api/v1/account` use `X-Account-ApiKey` in their request header. * All resource endpoints end with singular name and not plural. So we have `domain` instead of domains for domain resource endpoint. Likewise we have `sender` instead of senders for sender resource endpoint. * Body submitted for POST / PUT API calls as well as JSON response from SendPost API follow camelcase convention * All timestamps returned in response (created or submittedAt response fields) are UNIX nano epoch timestamp. SendPost uses conventional HTTP response codes to indicate the success or failure of an API request. * Codes in the `2xx` range indicate success. * Codes in the `4xx` range indicate an error owing due to unauthorize access, incorrect request parameters or body etc. * Code in the `5xx` range indicate an error with SendPost's servers ( internal service issue or maintenance ) > [!NOTE] > > In SendPost all responses return `created` in UNIX nano epoch timestamp. ## Authentication SendPost uses API keys for authentication. You can register a new SendPost API key at our [developer portal](https://app.sendpost.io/register). SendPost expects the API key to be included in all API requests to the server in a header that looks like the following: `X-SubAccount-ApiKey: AHEZEP8192SEGH` This API key is used for all Sub-Account level operations such as: * Sending emails * Retrieving stats regarding open, click, bounce, unsubscribe and spam * Uploading suppressions list * Verifying sending domains and more In addition to `X-SubAccount-ApiKey` you also have another API Key `X-Account-APIKey` which is used for Account level operations such as : * Creating and managing sub-accounts * Allocating IPs for your account * Getting overall billing and usage information * Email List validation * Creating and managing alerts and more You must look at individual API reference page to look at whether `X-SubAccount-ApiKey` is required or `X-Account-ApiKey` > [!NOTE] > > In case an incorrect API Key header is specified or if it is missed you will get HTTP Response 401 ( Unauthorized ) response from SendPost. ## HTTP Response Headers | Code | Reason | Details | | - | - | - | | 200 | Success | Everything went well | | 401 | Unauthorized | Incorrect or missing API header either ` X-SubAccount-ApiKey` or ` X-Account-ApiKey` | | 403 | Forbidden | Typically sent when resource with same name or details already exist | | 406 | Missing resource id | Resource id specified is either missing or doesn't exist | | 422 | Unprocessable entity | Request body is not in proper format | | 500 | Internal server error | Some error happened at SendPost while processing API request | | 503 | Service Unavailable | SendPost is offline for maintenance. Please try again later | ## API Reference SendX REST API can be broken down into two major sub-sections: * Sub-Account * Account Sub-Account API operations enable common email sending API use-cases like sending bulk email, adding new domains or senders for email sending programmatically, retrieving stats, adding suppressions etc. All Sub-Account API operations need to pass `X-SubAccount-ApiKey` header with every API call. The Account API operations allow users to manage multiple sub-accounts and manage IPs. A single parent SendPost account can have 100's of sub-accounts. You may want to create sub-accounts for different products your company is running or to segregate types of emails or for managing email sending across multiple customers of yours. ## SMTP Reference Simple Mail Transfer Protocol (SMTP) is a quick and easy way to send email from one server to another. SendPost provides an SMTP service that allows you to deliver your email via our servers instead of your own client or server. This means you can count on SendPost's delivery at scale for your SMTP needs. ### Integrating SMTP 1. Get the SMTP `username` and `password` from your SendPost account. 2. Set the server host in your email client or application to `smtp.sendpost.io`. This setting is sometimes referred to as the external SMTP server or the SMTP relay. 3. Set the `username` and `password`. 4. Set the port to `587` (or as specified below). ### SMTP Ports * For an unencrypted or a TLS connection, use port `25`, `2525` or `587`. * For a SSL connection, use port `465` * Check your firewall and network to ensure they're not blocking any of our SMTP Endpoints. SendPost supports STARTTLS for establishing a TLS-encrypted connection. STARTTLS is a means of upgrading an unencrypted connection to an encrypted connection. There are versions of STARTTLS for a variety of protocols; the SMTP version is defined in [RFC 3207](https://www.ietf.org/rfc/rfc3207.txt). To set up a STARTTLS connection, the SMTP client connects to the SendPost SMTP endpoint `smtp.sendpost.io` on port 25, 587, or 2525, issues an EHLO command, and waits for the server to announce that it supports the STARTTLS SMTP extension. The client then issues the STARTTLS command, initiating TLS negotiation. When negotiation is complete, the client issues an EHLO command over the new encrypted connection, and the SMTP session proceeds normally. > [!NOTE] > > If you are unsure which port to use, a TLS connection on port 587 is typically recommended. ## Sending email from your application ```javascript theme={null} "use strict"; const nodemailer = require("nodemailer"); async function main() { // create reusable transporter object using the default SMTP transport let transporter = nodemailer.createTransport({ host: "smtp.sendpost.io", port: 587, secure: false, // true for 465, false for other ports auth: { user: "" , // generated ethereal user pass: "", // generated ethereal password }, requireTLS: true, debug: true, logger: true, }); // send mail with defined transport object try { let info = await transporter.sendMail({ from: 'erlich@piedpiper.com', to: 'gilfoyle@piedpiper.com', subject: 'Test Email Subject', html: '

    Hello Geeks!!!

    ', }); console.log("Message sent: %s", info.messageId); } catch (e) { console.log(e) } } main().catch(console.error); ``` ```php theme={null} SMTPDebug = SMTP::DEBUG_CONNECTION; // Enable verbose debug output $mail->isSMTP(); // Send using SMTP $mail->Host = 'smtp.sendpost.io'; // Set the SMTP server to send through $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = ''; // SMTP username $mail->Password = ''; // SMTP password $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable implicit TLS encryption $mail->Port = 587; // TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS` //Recipients $mail->setFrom('erlich@piedpiper.com', 'Erlich'); $mail->addAddress('gilfoyle@piedpiper.com', 'Gilfoyle'); //Content $mail->isHTML(true); //Set email format to HTML $mail->Subject = 'Here is the subject'; $mail->Body = 'This is the HTML message body in bold!'; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; $mail->send(); echo 'Message has been sent'; } catch (Exception $e) { echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; } ``` ```python theme={null} #!/usr/bin/python3 import sys import os import re from smtplib import SMTP import ssl from email.mime.text import MIMEText SMTPserver = 'smtp.sendpost.io' PORT = 587 sender = 'erlich@piedpiper.com' destination = ['gilfoyle@piedpiper.com'] USERNAME = "" PASSWORD = "" # typical values for text_subtype are plain, html, xml text_subtype = 'plain' content="""\ Test message """ subject="Sent from Python" try: msg = MIMEText(content, text_subtype) msg['Subject']= subject msg['From'] = sender conn = SMTP(SMTPserver, PORT) conn.ehlo() context = ssl.create_default_context() conn.starttls(context=context) # upgrade to tls conn.ehlo() conn.set_debuglevel(True) conn.login(USERNAME, PASSWORD) try: resp = conn.sendmail(sender, destination, msg.as_string()) print("Send Mail Response: ", resp) except Exception as e: print("Send Email Error: ", e) finally: conn.quit() except Exception as e: print("Error:", e) ``` ```go theme={null} package main import ( "fmt" "net/smtp" "os" ) // Sending Email Using Smtp in Golang func main() { username := "" password := "" from := "erlich@piedpiper.com" toList := []string{"gilfoyle@piedpiper.com"} host := "smtp.sendpost.io" port := "587" // recommended // This is the message to send in the mail msg := "Hello geeks!!!" // We can't send strings directly in mail, // strings need to be converted into slice bytes body := []byte(msg) // PlainAuth uses the given username and password to // authenticate to host and act as identity. // Usually identity should be the empty string, // to act as username. auth := smtp.PlainAuth("", username, password, host) // SendMail uses TLS connection to send the mail // The email is sent to all address in the toList, // the body should be of type bytes, not strings // This returns error if any occured. err := smtp.SendMail(host+":"+port, auth, from, toList, body) // handling the errors if err != nil { fmt.Println(err) os.Exit(1) } fmt.Println("Successfully sent mail to all user in toList") } ``` ```java theme={null} // implementation 'com.sun.mail:javax.mail:1.6.2' import java.util.Properties; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SMTPConnect { // This address must be verified. static final String FROM = "erlich@piedpiper.com"; static final String FROMNAME = "Erlich Bachman"; // Replace recipient@example.com with a "To" address. If your account // is still in the sandbox, this address must be verified. static final String TO = "gilfoyle@piedpiper.com"; // Replace smtp_username with your SendPost SMTP user name. static final String SMTP_USERNAME = ""; // Replace smtp_password with your SendPost SMTP password. static final String SMTP_PASSWORD = ""; // SMTP Host Name static final String HOST = "smtp.sendpost.io"; // The port you will connect to on SendPost SMTP Endpoint. static final int PORT = 587; static final String SUBJECT = "SendPost SMTP Test (SMTP interface accessed using Java)"; static final String BODY = String.join( System.getProperty("line.separator"), "

    SendPost SMTP Test

    ", "

    This email was sent with SendPost using the ", "Javamail Package", " for Java." ); public static void main(String[] args) throws Exception { // Create a Properties object to contain connection configuration information. Properties props = System.getProperties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.port", PORT); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.debug", "true"); props.put("mail.smtp.auth", "true"); // Create a Session object to represent a mail session with the specified properties. Session session = Session.getDefaultInstance(props); // Create a message with the specified information. MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(FROM,FROMNAME)); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(TO)); msg.setSubject(SUBJECT); msg.setContent(BODY,"text/html"); // Create a transport. Transport transport = session.getTransport(); // Send the message. try { System.out.println("Sending..."); // Connect to SendPost SMTP using the SMTP username and password you specified above. transport.connect(HOST, SMTP_USERNAME, SMTP_PASSWORD); // Send the email. transport.sendMessage(msg, msg.getAllRecipients()); System.out.println("Email sent!"); } catch (Exception ex) { System.out.println("The email was not sent."); System.out.println("Error message: " + ex.getMessage()); System.out.println(ex); } // Close and terminate the connection. } } ``` Many programming languages support sending email using SMTP. This capability might be built into the programming language itself, or it might be available as an add-on, plug-in, or library. You can take advantage of this capability by sending email through SendPost from within application programs that you write. We have provided examples in Python3, Golang, Java, PHP, JS. # Allocate IP Source: https://docs.sendpost.io/api-reference/ip/allocate-a-new-ip put /account/ip/allocate Request allocation of a new dedicated IP address to your account. New IPs start in warmup state to build sender reputation gradually. **Warmup Process:** - New IPs have limited daily sending capacity - Volume increases automatically each day while `autoWarmupEnabled` is set - Full capacity typically reached after 30-45 days - Consistent, engagement-positive sending accelerates warmup **When to Allocate New IPs:** - Scaling beyond current IP capacity - Separating different email streams (transactional vs marketing) - Geographic IP requirements - Replacing an IP with poor reputation **Best Practices:** - Dedicated IPs require consistent volume (10k+ emails/month ideal) - Low volume on dedicated IPs can harm deliverability - Consider shared IPs for low-volume senders # Delete IP Source: https://docs.sendpost.io/api-reference/ip/delete-a-specific-ip delete /account/ip/{ip_id} Remove an IP address from your account. This action is irreversible. **⚠️ Before Deleting:** - Remove the IP from all IP pools first - Ensure no active sending relies on this IP - Consider impact on overall sending capacity **Note:** You cannot delete an IP that is currently assigned to an IP pool. # Get IP Source: https://docs.sendpost.io/api-reference/ip/get-a-specific-ip get /account/ip/{ip_id} Retrieve detailed information about a specific IP address, including its warmup status, type, and configuration. **Use Cases:** - Check warmup progress for a new dedicated IP - Verify IP configuration before adding to a pool - Debug deliverability issues by checking IP state - Monitor auto-warmup progress # List IPs Source: https://docs.sendpost.io/api-reference/ip/get-all-ips get /account/ip/ Retrieve all IP addresses allocated to your account. IPs are the foundation of your sending infrastructure and directly impact deliverability. **IP Types:** | Type | Value | Description | |------|-------|-------------| | Shared | `0` | IP shared with other SendPost senders. Cost-effective, reputation is pooled. | | Dedicated | `1` | Exclusive IP for your account. Full control over sender reputation. | **IP States:** | State | Value | Description | |-------|-------|-------------| | Warmup | `0` | New IP building reputation. Volume is limited and gradually increases. | | Normal | `1` | Fully warmed IP ready for normal sending volume. | **Warmup Information:** - `autoWarmupEnabled` - Whether SendPost is automatically increasing volume **Use Cases:** - Monitor IP warmup progress for new IPs - Audit shared vs dedicated IP allocation - Plan IP pool configurations - Check available sending capacity # Update IP Source: https://docs.sendpost.io/api-reference/ip/update-an-existing-ip put /account/ip/{ip_id} Modify settings for an existing IP address. Use this to manage warmup configuration. **Configurable Settings:** - `autoWarmupEnabled` - Enable/disable automatic warmup schedule **Use Cases:** - Pause auto-warmup during low-volume periods - Re-enable warmup after manual intervention - Adjust warmup settings based on sending patterns # Create IPPool Source: https://docs.sendpost.io/api-reference/ippools/create-a-new-ippool post /account/ippool Create a new IP pool to organize your sending infrastructure. Pools group IPs and third-party sending providers (TPSPs) for intelligent routing. **Pool Components:** - **IPs:** Dedicated IP addresses from your account - **TPSPs:** Third-party sending providers (SendGrid, Mailgun, etc.) **TPSP Types:** | Value | Provider | |-------|----------| | `0` | Amazon SES | | `1` | SendGrid | | `2` | Mailgun | | `3` | Custom SMTP | | `4` | PostMark | | `5` | Gmail | **Routing Strategies:** - `0` = Round Robin - Distribute traffic evenly - `1` = Email Provider - Route by recipient's mailbox provider - `2` = Volume Percentage - Split by defined percentages - `3` = Sending Domain - Route by your from domain **Use Cases:** - Separate transactional from marketing emails - Route high-volume traffic through TPSPs - Implement provider-specific routing for deliverability - Create backup pools for failover **Naming Best Practices:** - Use descriptive names: `Transactional_Orders`, `Marketing_Newsletter` - Include purpose: `HighPriority_Alerts`, `Bulk_Promotions` # Delete IPPool Source: https://docs.sendpost.io/api-reference/ippools/delete-a-specific-ippool delete /account/ippool/{ippool_id} Remove an IP pool from your account. This action is irreversible. **⚠️ Before Deleting:** - Ensure no sub-accounts are actively using this pool - Update any sending configurations that reference this pool - IPs in the pool will become unassigned (not deleted) **Note:** The default system pool cannot be deleted. # Get IPPool Source: https://docs.sendpost.io/api-reference/ippools/get-a-specific-ippool get /account/ippool/{ippool_id} Retrieve complete details about a specific IP pool, including all IPs and TPSPs assigned to it. **Response Includes:** - Pool name, ID, and creation date - Complete list of IPs with warmup status - All configured TPSPs with their settings - Current routing strategy and metadata - Warmup and monitoring configuration **Use Cases:** - Verify pool configuration before sending - Check which IPs/TPSPs are in a pool - Debug routing issues - Audit pool settings for compliance # List IPPools Source: https://docs.sendpost.io/api-reference/ippools/get-all-ippools get /account/ippool Retrieve all IP pools configured for your account. IP pools group IPs and third-party sending providers (TPSPs) for intelligent traffic routing. **Pool Types:** | Type | Value | Description | |------|-------|-------------| | Shared | `0` | Pool uses shared IPs (shared with other SendPost customers) | | Dedicated | `1` | Pool uses dedicated IPs (exclusive to your account) | **Routing Strategies:** | Strategy | Value | Description | |----------|-------|-------------| | Round Robin | `0` | Distribute traffic evenly across pool members | | Email Provider | `1` | Route based on recipient's mailbox provider (Gmail, Yahoo, etc.) | | Volume Percentage | `2` | Split traffic by defined percentages | | Sending Domain | `3` | Route based on your sending domain | **Use Cases:** - Audit your sending infrastructure configuration - View IPs and TPSPs in each pool - Plan routing strategy changes - Verify pool setup before sending campaigns # Routing Strategies and Metadata Source: https://docs.sendpost.io/api-reference/ippools/routing Description of your new file. ### routing\_strategy 0 (RoundRobinStrategy) In RoundRobinStrategy all your emails are fairly shared between all your IPs and TPSPs The payload for routingMetaData for RoundRobinStrategy is: | **Key** | **Value** | | :- | :- | | routingStrategy | 0 | | routingMetaData | "" | For example, if you have IP 3.238.19.86 and TPSPs Sendgrid and Mailgun and send 6 emails then 2 emails will be sent from 3.238.19.86, Mailgun and Sengrid. ### routing\_strategy 1 (EmailProviderStrategy) In the EmailProviderStrategy we can assign IPs and TPSPs to the specific email provider. Existing email provider types: | **Id** | **Description** | | :- | :- | | 0 | Email type Gmail | | 1 | Email type Yahoo | | 2 | Email type AOL | | 3 | Email type Microsoft | | 4 | Email type Comcast | | 5 | Email type Yandex | | 6 | Email type GMX | | 7 | Email type Mailru | | 8 | Email type Icloud | | 9 | Email type Zoho | | 10 | Email type QQ | | 11 | Email type default | | **Key** | **Value** | | :- | :- | | routingStrategy | 1 | | routingMetaData | JsonPayload | JsonPayload example: ```json theme={null} { "0": "[\"IP_100\",\"IP_105\"]", "1": "[\"TPSP_101\"]", "others": "[\"IP_102\",\"TPSP_103\",\"IP_104\"]" } ``` On the left side, you can see the email types: 0 is Gmail, 1 is Yahoo, and 'others' in this case all email addresses that don't belong to Yahoo or Gmail, the left side key is in the string format. Currently, for the right side, the format is an Array of strings in the format of "Entity\_ID". Where 'Entity' could be 'IP' or 'TPSP' (third-party sending provider). For example, the 'IP\_' prefix means that the entity is IP, and 100 in "IP\_100" mean that the ID of this IP is 100. For example, the 'TPSP\_' prefix means that the entity is TPSP, and 101 in "TPSP\_101" mean that the ID of this TPSP is 101. The metadata above means: that for Gmail we send emails fairly between IPs with ID 105 and ID 100; and for Yahoo, we send emails from TPSP with ID 101; and for all the rest email types we send fairly from the TPSP with ID 103 and from IP with ID 104 and 102. ### routing\_strategy 2 (VolumePercentageStrategy) In the VolumePercentageStrategy we can assign volumes to the specific IPs and TPSPs. | **Key** | **Value** | | :- | :- | | routingStrategy | 2 | | routingMetaData | JsonPayload | JsonPayload example: ```json theme={null} { "IP_100": "2", "IP_101": "3", "TPSP_102": "1", "TPSP_103": "4" } ``` Currently, for the left side, the format is a string in the format of "Entity\_ID". Where 'Entity' could be 'IP' or 'TPSP' (third-party sending provider). And for the right side, the volume number of emails that we send (also in the string format). For example, the 'IP\_' prefix means that the entity is IP, and 100 in "IP\_100" mean that the ID of this IP is 100. For example, the 'TPSP\_' prefix means that the entity is TPSP, and 101 in "TPSP\_101" mean that the ID of this TPSP is 101. The metadata above means: that, for example, if we send 20 emails, 4 go from IP with ID 100, 6 go from IP with ID 101, 2 go from TPSP with ID 102, and 8 go from TPSP with ID 103. ### routing\_strategy 3 (SendingDomainStrategy) In the SendingDomainStrategy we can assign IPs and TPSPs to the specific domains that we are sending from. | **Key** | **Value** | | - | - | | routingStrategy | 3 | | routingMetaData | JsonPayload | JsonPayload example: ```json theme={null} { "sendx.io": "[\"TPSP_100\",\"IP_105\"]", "sendpost.io": "[\"IP_101\"]", "others": "[\"IP_102\",\"IP_103\",\"TPSP_104\"]" } ``` On the left side, you can see the domains, in this case, it's [sendx.io](http://sendx.io) and [sendpost.io](http://sendpost.io), and 'others'. The email would be put in the 'others' category if its domain doesn't belong to [sendx.io](http://sendx.io) or [sendpost.io](http://sendpost.io). Currently, for the right side, the format is an Array of strings in the format of "Entity\_ID". Where 'Entity' could be 'IP' or 'TPSP' (third-party sending provider). For example, the 'IP\_' prefix means that the entity is IP, and 100 in "IP\_100" mean that the ID of this IP is 100. For example, the 'TPSP\_' prefix means that the entity is TPSP, and 101 in "TPSP\_101" mean that the ID of this TPSP is 101. The metadata above means: that, for example, if we send emails from [t1@sendx.io](mailto:t1@sendx.io), [t2@sendx.io](mailto:t2@sendx.io), [t1@sendpost.io](mailto:t1@sendpost.io), [t1@gmail.com](mailto:t1@gmail.com), [t2@gmail.com](mailto:t2@gmail.com), [t3@gmail.com](mailto:t3@gmail.com), [t4@yahoo.com](mailto:t4@yahoo.com) The [sendx.io](http://sendx.io) emails ([t1@sendx.io](mailto:t1@sendx.io), [t2@sendx.io](mailto:t2@sendx.io)) will be sent from TPSP with ID 100 and IP with ID 105. The [sendpost.io](http://sendpost.io) emails will be sent from IP with ID 101. The 'others' emails ([t1@gmail.com](mailto:t1@gmail.com), [t2@gmail.com](mailto:t2@gmail.com), [t3@gmail.com](mailto:t3@gmail.com), [t4@yahoo.com](mailto:t4@yahoo.com)) will be sent from IP with ID 102 and 103, and TPSP with ID 104. # Update IPPool Source: https://docs.sendpost.io/api-reference/ippools/update-an-existing-ippool put /account/ippool/{ippool_id} Modify an existing IP pool's configuration, including name, IPs, TPSPs, and routing strategy. **What Can Be Updated:** - Pool name - IP addresses assigned to the pool - Third-party sending providers (TPSPs) - Routing strategy and metadata - Warmup and monitoring settings **Use Cases:** - Add new IPs to scale capacity - Remove underperforming IPs - Change routing strategy - Add/remove TPSP integrations - Rename pool for clarity **Best Practices:** - Test routing changes during low-traffic periods - Ensure at least one sending option remains in the pool - Document changes for team awareness # Get Message Source: https://docs.sendpost.io/api-reference/message/retrieve-a-specific-message get /account/message/{message_id} Retrieve complete details about a specific email message, including full event timeline and metadata. **Response Includes:** - Full message details (sender, recipients, subject) - Complete event timeline (submitted, sent, delivered, opened, clicked) - Bounce/drop information with reasons - IP and pool used for sending - Click and open tracking data **Use Cases:** - Debug why a specific email wasn't delivered - Customer support - provide delivery proof - Audit trail for compliance requirements - Analyze engagement for specific messages # Get Account Aggregate Stats Source: https://docs.sendpost.io/api-reference/stats-a/get-account-aggregate-stats get /account/stat/aggregate Retrieve summarized email statistics across all sub-accounts for a date range. Returns a single aggregated record—perfect for high-level reporting and dashboards. **Use Cases:** - Annual email program review - Quarterly business reports - Month-over-month comparison - Board-level metrics - ROI calculations for email program **Example:** Get full year stats for 2024: ``` GET /account/stat/aggregate?from=2024-01-01&to=2024-12-31 ``` **Note:** Maximum date range is 366 days (1 year). # Get Account Group Aggregate Stats Source: https://docs.sendpost.io/api-reference/stats-a/get-account-aggregate-stats-by-group get /account/stat/aggregate/group Retrieve summarized email statistics for a specific group across all sub-accounts. Returns a single aggregated record for the group—ideal for campaign reporting. **Use Cases:** - Annual performance report for a specific product integration - Compare total metrics for different campaigns - Summarize email performance for a specific customer segment - Calculate ROI for a marketing campaign by group **Example:** Get yearly stats for Shopify integration: ``` GET /account/stat/aggregate/group?group=shopify&from=2024-01-01&to=2024-12-31 ``` **Note:** Maximum date range is 366 days (1 year). # List Account Stats Source: https://docs.sendpost.io/api-reference/stats-a/get-all-account-stats get /account/stat Retrieve daily email statistics aggregated across all sub-accounts. Returns one record per day within the date range—ideal for organization-wide reporting. **Metrics Per Day:** | Metric | Description | |--------|-------------| | `processed` | Total emails submitted across all sub-accounts | | `delivered` | Successfully delivered to recipients | | `dropped` | Blocked before sending | | `hardBounced` | Permanent delivery failures | | `softBounced` | Temporary delivery failures | | `opens` | Total email opens | | `clicks` | Total link clicks | | `unsubscribed` | Recipients who unsubscribed | | `spams` | Spam complaints received | **Use Cases:** - Organization-wide email performance dashboard - Billing and usage tracking across all sub-accounts - Executive reporting for email program health - Trend analysis across your entire email operation **Note:** Maximum date range is 31 days. # List Account Group Stats Source: https://docs.sendpost.io/api-reference/stats-a/get-all-account-stats-by-group get /account/stat/group Retrieve daily email statistics for a specific group across all sub-accounts. Returns one record per day, filtered by the group/tag you specify. **What are Groups?** Groups (tags) are labels attached to emails when sending. They enable segmented analytics across your entire account. **Common Group Strategies:** | Strategy | Example Groups | |----------|----------------| | By Product | `shopify`, `wordpress`, `api-direct` | | By Type | `transactional`, `marketing`, `alerts` | | By Team | `sales-team`, `support`, `engineering` | | By Campaign | `black-friday-2024`, `summer-sale` | **Use Cases:** - Compare performance across products/integrations - Track specific campaign performance account-wide - Analyze transactional vs marketing metrics - Benchmark different teams' email performance **Note:** Maximum date range is 31 days. # Get Aggregate Stats Source: https://docs.sendpost.io/api-reference/stats/get-aggregate-stats get /account/subaccount/stat/{subaccount_id}/aggregate Retrieve summarized email statistics for a sub-account over a date range. Unlike daily stats, this returns a single record with totals across all days—ideal for high-level reporting. **Response includes total counts for:** - `processed` - Total emails submitted - `delivered` - Successfully delivered - `dropped` - Blocked before sending - `hardBounced` / `softBounced` - Bounce breakdowns - `opens` / `clicks` - Engagement totals - `unsubscribed` / `spams` - Negative signals **Use Cases:** - Monthly performance reports - Executive dashboards - Billing period summaries - Year-over-year comparisons - SLA compliance reports **Example:** To get Q1 2024 totals: ``` GET /account/subaccount/stat/11/aggregate?from=2024-01-01&to=2024-03-31 ``` **Note:** Maximum date range is 366 days (1 year). # Get Group Aggregate Stats Source: https://docs.sendpost.io/api-reference/stats/get-aggregated-stats-by-group get /account/subaccount/stat/{subaccount_id}/group Retrieve aggregated email statistics filtered by a specific group/tag. Groups are labels you assign when sending emails to categorize and segment your analytics. **What are Groups?** Groups (also called tags) are strings you attach to emails when sending. They help you: - Track different email types (transactional vs marketing) - Segment by campaign or feature - Compare performance across categories **Setting Groups When Sending:** ```json { "from": { "email": "orders@shop.com" }, "to": [{ "email": "customer@example.com" }], "subject": "Order Confirmation", "groups": ["order-confirmations", "transactional"] } ``` **Use Cases:** - Compare welcome email vs password reset performance - Track marketing campaign performance by campaign ID - Measure transactional vs promotional email metrics - Analyze A/B test results by variant group **Example:** Get stats for "welcome-emails" group: ``` GET /account/subaccount/stat/11/group?group=welcome-emails&from=2024-01-01&to=2024-03-31 ``` **Note:** Maximum date range is 366 days. # List Stats Source: https://docs.sendpost.io/api-reference/stats/get-all-stats get /account/subaccount/stat/{subaccount_id} Retrieve daily email statistics for a specific sub-account. Returns one record per day within the date range, perfect for charting trends and identifying patterns. **Metrics Per Day:** | Metric | Description | |--------|-------------| | `processed` | Emails submitted to SendPost | | `delivered` | Successfully delivered to recipient's mailbox | | `dropped` | Blocked before sending (suppressed, invalid, etc.) | | `hardBounced` | Permanent failures (invalid address, domain doesn't exist) | | `softBounced` | Temporary failures (mailbox full, server down) | | `opens` | Total email opens (includes multiple opens per recipient) | | `clicks` | Total link clicks | | `unsubscribed` | Recipients who unsubscribed | | `spams` | Emails marked as spam by recipients | **Key Rates to Calculate:** - Delivery Rate = `delivered / processed × 100` - Open Rate = `opens / delivered × 100` - Click Rate = `clicks / delivered × 100` - Bounce Rate = `(hardBounced + softBounced) / processed × 100` **Use Cases:** - Daily performance dashboard - Week-over-week trend analysis - Identifying delivery issues early - SLA monitoring and reporting **Note:** Maximum date range is 31 days. Both `from` and `to` dates are inclusive. # Create Sub-Account Source: https://docs.sendpost.io/api-reference/sub-account/create-a-new-sub-account post /account/subaccount/ Create a new sub-account to segment your email sending. Each sub-account gets its own API key, suppression list, and statistics. **What You Get:** - Unique `X-SubAccount-ApiKey` for authentication - Isolated email statistics - Separate suppression management - Independent domain configuration - Optional SMTP credentials **Naming Best Practices:** - Use descriptive names: `Transactional_Orders`, `Marketing_Newsletter` - Include environment: `Production_Alerts`, `Staging_Tests` - For multi-tenant: `Client_CompanyName` **Use Cases:** - New application or microservice needing email - Onboarding a new client in multi-tenant setup - Creating isolated testing environment - Separating email streams for analytics # Delete Sub-Account Source: https://docs.sendpost.io/api-reference/sub-account/delete-a-specific-sub-account delete /account/subaccount/{subaccount_id} Remove a sub-account from your organization. This action is irreversible. **⚠️ Before Deleting:** - Export any needed statistics or suppression lists - Update applications using this sub-account's API key - Ensure no active email sending relies on this sub-account **What Gets Deleted:** - All sub-account configuration - Associated API keys (will stop working) - Statistics are retained for your account records **Note:** The default sub-account (type `0`) cannot be deleted. # Get Sub-Account Source: https://docs.sendpost.io/api-reference/sub-account/get-a-specific-sub-account get /account/subaccount/{subaccount_id} Retrieve detailed information about a specific sub-account, including API keys, SMTP credentials, and configuration. **Response Includes:** - Sub-account name and ID - API key for sub-account authentication - SMTP credentials (if enabled) - Team members with access - Labels/tags for categorization - Creation timestamp # List Sub-Accounts Source: https://docs.sendpost.io/api-reference/sub-account/get-all-sub-accounts get /account/subaccount/ Retrieve all sub-accounts under your main account. Sub-accounts allow you to segment email sending for different applications, brands, or use cases. **Sub-Account Types:** | Type | Value | Description | |------|-------|-------------| | Default | `0` | Primary sub-account created with your account (cannot be deleted) | | Custom | `1` | Additional sub-accounts you create | **Each Sub-Account Has:** - Unique `X-SubAccount-ApiKey` for API authentication - Independent suppression list - Isolated email statistics - Own domain configurations - SMTP credentials (if enabled) **Use Cases:** - Separate transactional and marketing emails - Multi-tenant SaaS applications (one sub-account per customer) - Different brands or product lines - Development/staging/production environments **Note:** `isPlus` indicates SendX Plus customers with premium features. # Update Sub-Account Source: https://docs.sendpost.io/api-reference/sub-account/update-an-existing-sub-account put /account/subaccount/{subaccount_id} Modify settings for an existing sub-account. Use this to rename sub-accounts, update labels, or modify configuration. **What Can Be Updated:** - Sub-account name - Labels/tags for categorization - Other configuration settings **Use Cases:** - Rename sub-account for clarity - Update labels for organizational changes - Modify settings after initial setup # Create Suppressions Source: https://docs.sendpost.io/api-reference/suppression/create-new-suppressions post /subaccount/suppression Add email addresses to your suppression list to prevent future emails from being sent. This is essential for maintaining sender reputation and compliance. **When to Use Each Type:** | Type | Use When | |------|----------| | `hardBounce` | You know an address is permanently invalid | | `manual` | Processing do-not-contact requests from support | | `unsubscribe` | Syncing unsubscribes from external systems | | `spamComplaint` | Importing complaints from other providers | **Common Use Cases:** - **Migration:** Import suppression list from previous email provider - **CRM Sync:** Add unsubscribes from your marketing platform - **Bulk Cleanup:** Add known invalid addresses from data cleaning - **Support Tickets:** Honor do-not-contact requests **Best Practices:** - Import historical bounce data when migrating providers - Sync unsubscribes immediately when received from external sources - Process support-requested suppressions within 24 hours - Use `manual` for addresses you want to suppress without categorization # Delete Suppressions Source: https://docs.sendpost.io/api-reference/suppression/delete-suppressions delete /subaccount/suppression Remove email addresses from your suppression list, allowing them to receive emails again. **⚠️ Important: Use with caution!** Re-enabling sending to previously suppressed addresses can harm your sender reputation if used incorrectly. **Valid Use Cases:** - User confirms their valid email was incorrectly bounced - Manual suppression was added by mistake - User explicitly requests re-subscription after unsubscribing - Testing/development addresses that were suppressed **Not Recommended:** - Bulk removing hard bounces without individual verification - Removing spam complaints (users rarely want to receive emails again) - Attempting to re-engage addresses that bounced **Best Practice:** Before removing a suppression, verify with the recipient that they want to receive emails and that their address is valid. # List Suppressions Source: https://docs.sendpost.io/api-reference/suppression/get-all-suppressions get /subaccount/suppression Retrieve the suppression list for your sub-account. Suppressions are email addresses that should not receive emails to protect your sender reputation and ensure compliance. **Suppression Types:** | Type | Reason Code | Description | |------|-------------|-------------| | `manual` | 0 | Manually added by your team | | `unsubscribe` | 1 | User clicked unsubscribe link | | `hardBounce` | 2 | Permanent delivery failure (invalid address) | | `spamComplaint` | 3 | User marked email as spam | **Why Suppressions Matter:** - **Reputation Protection:** Repeatedly sending to bounced addresses damages sender reputation - **Compliance:** Required for CAN-SPAM, GDPR, and other regulations - **Cost Savings:** Avoid paying to send undeliverable emails - **Deliverability:** ISPs penalize senders with high bounce/complaint rates **Use Cases:** - Export suppression list for compliance audits - Sync suppressions with your CRM or marketing platform - Review recent bounces to identify data quality issues - Monitor spam complaints for content/targeting problems **Pagination:** Use `limit` and `offset` for large suppression lists. **Note:** Maximum date range is 60 days. # Create Webhook Source: https://docs.sendpost.io/api-reference/webhook/create-a-new-webhook post /account/webhook Create a new webhook to receive real-time notifications for email events. Your endpoint will receive HTTP POST requests with event data as they occur. **Endpoint Requirements:** - Must be a publicly accessible absolute `http://` or `https://` URL (use HTTPS) - Should return 2xx status within 30 seconds - Handle potential duplicate events (use event ID for deduplication) - Implement retry/queue logic for reliability **Choosing Events:** - **Engagement Tracking:** `uniqueOpened`, `uniqueClicked` for metrics - **Full History:** `opened`, `clicked` for complete event logs - **Delivery Monitoring:** `delivered`, `hardBounced`, `softBounced` - **Compliance:** `unsubscribed`, `spam` **Best Practices:** - Only enable events you actually need - Store events before processing (async processing) - Implement idempotency using event IDs - Set up monitoring for webhook failures **Webhook Payload Example:** ```json { "eventId": "evt_123", "event": "delivered", "messageId": "msg_456", "recipient": "user@example.com", "timestamp": "2024-01-15T10:30:00Z" } ``` # Delete Webhook Source: https://docs.sendpost.io/api-reference/webhook/delete-a-specific-webhook delete /account/webhook/{webhook_id} Remove a webhook from your account. After deletion, no further events will be sent to that endpoint. **Before Deleting:** - Ensure your application doesn't rely on these events - Consider updating to a new webhook instead if you're migrating **Note:** Events that occurred before deletion are not affected. Historical data remains intact. # Get Webhook Source: https://docs.sendpost.io/api-reference/webhook/get-a-specific-webhook get /account/webhook/{webhook_id} Retrieve detailed information about a specific webhook, including its endpoint URL and enabled events. **Use Cases:** - Verify webhook configuration - Debug event delivery issues - Check enabled events for a webhook - Audit webhook settings # List Webhooks Source: https://docs.sendpost.io/api-reference/webhook/get-all-webhooks get /account/webhook Retrieve all configured webhooks for your account. Webhooks enable real-time notifications when email events occur, allowing you to build reactive applications. **Supported Events:** | Event | Description | |-------|-------------| | `processed` | Email accepted and queued for delivery | | `dropped` | Email blocked (suppressed, invalid, policy) | | `delivered` | Email successfully delivered to recipient | | `hardBounced` | Permanent delivery failure | | `softBounced` | Temporary delivery failure | | `opened` | Recipient opened the email (all opens) | | `uniqueOpened` | First open per recipient only | | `clicked` | Recipient clicked a link (all clicks) | | `uniqueClicked` | First click per recipient only | | `unsubscribed` | Recipient unsubscribed | | `spam` | Recipient marked email as spam | **Use Cases:** - Audit configured webhook endpoints - Verify webhook URLs are correct - Review enabled events per webhook - Debug webhook delivery issues # SendPost Webhook Object Source: https://docs.sendpost.io/api-reference/webhook/sendpost-webhook-object webhook SendPostWebhooks When you use SendPost API to send an email, SendPost generates webhook events throughout the email lifecycle. Each webhook event contains an `event` object and an `emailMessage` object. The `emailMessage` object remains the same across all events for a given email, allowing you to correlate events using the `messageID`. For a detailed explanation of the email lifecycle and what each event type means, see [Understanding Webhook Event Lifecycle](/api-reference/webhook/understanding-webhook-event-lifecycle). ## Complete Webhook Payload Structure Every webhook payload sent by SendPost follows this structure: ```json theme={null} { "event": { "eventID": "string", "type": "integer", "messageID": "string", "submittedAt": "integer", "smtpCode": "integer", "smtpDescription": "string", "validationStatus": "string", "eventMetadata": { "clickedURL": "string", "smtpCode": "integer", "smtpDescription": "string", "userAgent": { "Family": "string", "Major": "string", "Minor": "string", "Patch": "string" }, "os": { "Family": "string", "Major": "string", "Minor": "string", "Patch": "string", "PatchMinor": "string" }, "device": { "Family": "string", "Brand": "string", "Model": "string" }, "geo": { "city": "string", "country": "string", "countryCode": "string", "region": "string", "regionCode": "string", "postalCode": "string", "latitude": "number", "longitude": "number", "timezone": "string" }, "trackedIP": "string", "rawUserAgent": "string" } }, "emailMessage": { "messageID": "string", "from": { "email": "string", "name": "string" }, "to": [ { "email": "string", "name": "string" } ], "subject": "string", "emailType": "string", "ipID": "integer", "ipPoolID": "integer", "ipPool": "string", "publicIP": "string", "headers": { "key": "value" }, "groups": ["string"] } } ``` *** ## Event Object Fields The `event` object contains information about the specific webhook event that occurred. | Field | Type | Description | Present In | | - | - | - | - | | `eventID` | string | Unique identifier for this specific event. Use this to deduplicate events if your webhook endpoint receives the same event multiple times due to retries. | All events | | `type` | integer | Numeric code indicating the type of event. See the Event Types table below for all possible values. | All events | | `messageID` | string | Unique identifier for the email message. This ID remains consistent across all events for the same email, allowing you to correlate events throughout the email lifecycle. | All events | | `submittedAt` | integer | Unix timestamp (in seconds) indicating when this specific event occurred in SendPost. For example, when the email was processed, delivered, opened, or clicked. Use this to track the exact timing of each event in the email lifecycle. | All events | | `smtpCode` | integer | The SMTP response code returned by the recipient's mail server. Common codes: 200-299 (success), 400-499 (temporary failure), 500-599 (permanent failure). | Delivered, SoftBounced, HardBounced | | `smtpDescription` | string | Human-readable description of the SMTP response. Provides context about why an email was delivered, bounced, or rejected. | Delivered, SoftBounced, HardBounced | | `validationStatus` | string | The real-time list cleaning result for the email: `valid`, `invalid`, `catch all` or `unknown`. See [Real-Time Validation Results](/api-reference/webhook/validation-results). | Validation | | `eventMetadata` | object | Contains additional metadata specific to the event type. The fields present vary depending on the event type. | All events (contents vary) | ### Event Types Every event generated as SendPost webhook will have a `type` field in the event object: | Webhook Event | Type Field Value | Description | | - | - | - | | Processed | 0 | Email has been accepted by SendPost and is queued for delivery | | Dropped | 1 | Email was not sent due to suppression list, invalid recipient, or policy violation | | Delivered | 2 | Email was successfully delivered to the recipient's mail server | | SoftBounced | 3 | Email delivery temporarily failed; SendPost will retry delivery | | HardBounced | 4 | Email delivery permanently failed; the recipient address is invalid or doesn't exist | | Opened | 5 | Recipient opened the email (requires tracking pixel) | | Clicked | 6 | Recipient clicked a link in the email (requires link tracking) | | Unsubscribed | 7 | Recipient unsubscribed via the unsubscribe link | | Spam | 8 | Recipient marked the email as spam | | SMTP Dropped | 26 | Email was dropped at the SMTP stage, for example because real-time list cleaning found the address invalid | | Validation | 82 | Real-time list cleaning result for the email, in `validationStatus` (Real-Time List Cleaning add-on). See [Real-Time Validation Results](/api-reference/webhook/validation-results) | *** ## Event Metadata Fields The `eventMetadata` object contains event-specific information. Different fields are populated depending on the event type. | Field | Type | Description | Present In | | - | - | - | - | | `clickedURL` | string | The full URL that the recipient clicked. Only present when a link click is tracked. | Clicked | | `smtpCode` | integer | Duplicate of `event.smtpCode` for convenience. The SMTP response code from the recipient's mail server. | Delivered, SoftBounced, HardBounced | | `smtpDescription` | string | Duplicate of `event.smtpDescription` for convenience. Human-readable SMTP response description. | Delivered, SoftBounced, HardBounced | | `userAgent` | object | Parsed user agent information identifying the email client or browser used to open/click. | Opened, Clicked | | `os` | object | Parsed operating system information of the device used to open/click. | Opened, Clicked | | `device` | object | Parsed device information identifying the hardware used to open/click. | Opened, Clicked | | `geo` | object | Geographic location information based on the IP address of the recipient when they opened/clicked. | Opened, Clicked | | `trackedIP` | string | The IP address of the recipient when they clicked a link. | Clicked | | `rawUserAgent` | string | The raw, unparsed User-Agent string from the recipient's browser or email client. | Opened, Clicked | ### userAgent Object Fields The `userAgent` object provides parsed browser/email client information: | Field | Type | Description | Example | | - | - | - | - | | `Family` | string | Name of the browser or email client | "Chrome", "Safari", "Outlook", "Gmail" | | `Major` | string | Major version number of the browser/client | "91", "15", "16" | | `Minor` | string | Minor version number of the browser/client | "0", "4", "2" | | `Patch` | string | Patch version number of the browser/client | "4472", "1", "0" | ### os Object Fields The `os` object provides parsed operating system information: | Field | Type | Description | Example | | - | - | - | - | | `Family` | string | Name of the operating system | "Windows", "Mac OS X", "iOS", "Android", "Linux" | | `Major` | string | Major version number of the OS | "10", "14", "12" | | `Minor` | string | Minor version number of the OS | "0", "5", "1" | | `Patch` | string | Patch version number of the OS | "19041", "1", "0" | | `PatchMinor` | string | Additional patch version detail (if available) | "1" | ### device Object Fields The `device` object provides parsed hardware device information: | Field | Type | Description | Example | | - | - | - | - | | `Family` | string | General category or name of the device | "iPhone", "iPad", "Samsung", "Other" | | `Brand` | string | Brand/manufacturer of the device | "Apple", "Samsung", "Google", "Unknown" | | `Model` | string | Specific model of the device | "iPhone 13", "Galaxy S21", "Pixel 6" | ### geo Object Fields The `geo` object provides geographic location information based on IP geolocation: | Field | Type | Description | Example | | - | - | - | - | | `countryCode` | string | ISO 3166-1 alpha-2 country code | "US", "GB", "DE" | | `regionCode` | string | Region/state code | "CA", "NY", "TX" | | `postalCode` | string | Postal or ZIP code | "94102", "10001", "SW1A 1AA" | | `timezone` | string | IANA timezone identifier | "America/Los\_Angeles", "Europe/London" | > [!NOTE] > > Geographic data is derived from IP address lookups and may not always be 100% accurate. The precision depends on the IP geolocation database and the nature of the recipient's network connection. *** ## Email Message Object Fields The `emailMessage` object contains information about the original email that was sent. This object remains identical across all webhook events for the same email. | Field | Type | Description | Present In | | - | - | - | - | | `messageID` | string | Unique identifier for the email message. Matches `event.messageID` and can be used to correlate events across the email lifecycle. | All events | | `from` | object | The sender information for the email. Contains the sender's email address and display name. | All events | | `to` | array | Array of recipient objects. Each object contains the recipient's email address and display name. | All events | | `subject` | string | The subject line of the email as it was sent. | All events | | `emailType` | string | The classification type of the email. Common values include `transactional` for system-generated emails (receipts, password resets, notifications) and `marketing` for promotional content. This helps distinguish email purposes for analytics and compliance. | All events | | `ipID` | integer | The unique identifier of the specific IP address used to send this email. Use this to track which IP was used for delivery, useful for troubleshooting deliverability issues. | All events | | `ipPoolID` | integer | The unique identifier of the IP pool from which the sending IP was selected. IP pools group multiple IPs together for load balancing and reputation management. | All events | | `ipPool` | string | The name of the IP pool used for sending this email. This is the human-readable name assigned to the IP pool, making it easier to identify which pool was used without looking up the ID. | All events | | `publicIP` | string | The actual public IP address used by SendPost to deliver this email to the recipient's mail server. This is the IP that receiving servers see and is important for monitoring sender reputation. | All events | | `headers` | object | Key-value pairs of custom headers that were included in the original email request. Use these for tracking campaigns, orders, or custom metadata. | All events (if headers were sent) | | `groups` | array | Array of group names/tags that were assigned to the email for classification and filtering purposes. | All events (if groups were assigned) | ### from Object Fields The `from` object contains sender information: | Field | Type | Description | Example | | - | - | - | - | | `email` | string | The email address of the sender | "[support@example.com](mailto:support@example.com)" | | `name` | string | The display name of the sender (shown in email clients) | "Support Team", "John Doe" | ### to Array Item Fields Each item in the `to` array represents a recipient: | Field | Type | Description | Example | | - | - | - | - | | `email` | string | The email address of the recipient | "[customer@example.com](mailto:customer@example.com)" | | `name` | string | The display name of the recipient | "John Doe", "Jane Smith" | ### headers Object The `headers` object is a key-value store for custom headers: | Field | Type | Description | Example | | - | - | - | - | | `{key}` | string | Any custom header key you included in your email request | `"X-Campaign-Id": "summer-2024"` | > [!NOTE] > > Custom headers you send with your email are preserved and returned in all webhook events. This allows you to track emails throughout their lifecycle using your own identifiers. ### groups Array The `groups` array contains classification tags: | Field | Type | Description | Example | | - | - | - | - | | `groups[n]` | string | A group/tag name assigned to categorize the email | "transactional", "marketing", "order-confirmation" | *** ## SMTP Code and Description in Webhook Events SMTP codes and descriptions provide detailed information about email delivery status. These fields are available in specific webhook events to help you understand delivery outcomes. ### Availability by Event Type | Event Type | smtpCode Available | smtpDescription Available | Location in Payload | | - | - | - | - | | Processed (0) | ❌ No | ❌ No | N/A | | Dropped (1) | ❌ No | ❌ No | N/A | | Delivered (2) | ✅ Yes | ✅ Yes | `event.smtpCode`, `event.smtpDescription`, `event.eventMetadata.smtpCode`, `event.eventMetadata.smtpDescription` | | SoftBounced (3) | ✅ Yes | ✅ Yes | `event.smtpCode`, `event.smtpDescription`, `event.eventMetadata.smtpCode`, `event.eventMetadata.smtpDescription` | | HardBounced (4) | ✅ Yes | ✅ Yes | `event.smtpCode`, `event.smtpDescription`, `event.eventMetadata.smtpCode`, `event.eventMetadata.smtpDescription` | | Opened (5) | ❌ No | ❌ No | N/A | | Clicked (6) | ❌ No | ❌ No | N/A | | Unsubscribed (7) | ❌ No | ❌ No | N/A | | Spam (8) | ❌ No | ❌ No | N/A | ### Common SMTP Codes | Code Range | Category | Description | | - | - | - | | 200-299 | Success | Email was accepted and delivered successfully | | 250 | Success | Requested mail action completed | | 421 | Temporary | Service not available, try again later | | 450 | Temporary | Mailbox unavailable (busy or temporarily blocked) | | 451 | Temporary | Local error in processing | | 452 | Temporary | Insufficient storage | | 500 | Permanent | Syntax error, command unrecognized | | 550 | Permanent | Mailbox unavailable (not found or policy rejection) | | 551 | Permanent | User not local | | 552 | Permanent | Message size exceeds limit | | 553 | Permanent | Mailbox name not allowed | | 554 | Permanent | Transaction failed | ### Example: Delivered Event with SMTP Code ```json theme={null} { "event": { "eventID": "edhg-123gh-afasdf-124egh", "type": 2, "messageID": "mjhl-1401-sasdf-129324", "submittedAt": 1704067200, "smtpCode": 250, "smtpDescription": "email delivered successfully", "eventMetadata": { "smtpCode": 250, "smtpDescription": "email delivered successfully" } }, "emailMessage": { "messageID": "mjhl-1401-sasdf-129324", "from": { "email": "support@example.com", "name": "Support Team" }, "to": [ { "email": "customer@example.com", "name": "John Doe" } ], "subject": "Welcome to Our Service", "emailType": "transactional", "ipID": 42, "ipPoolID": 7, "ipPool": "transactional-pool", "publicIP": "192.0.2.100", "headers": { "X-Campaign-Id": "12345", "X-Custom-Header": "value" } } } ``` ### Example: HardBounced Event with SMTP Code ```json theme={null} { "event": { "eventID": "edhg-456gh-afasdf-124egh", "type": 4, "messageID": "mjhl-1401-sasdf-129324", "submittedAt": 1704067200, "smtpCode": 550, "smtpDescription": "Mailbox unavailable", "eventMetadata": { "smtpCode": 550, "smtpDescription": "Mailbox unavailable" } }, "emailMessage": { "messageID": "mjhl-1401-sasdf-129324", "from": { "email": "support@example.com", "name": "Support Team" }, "to": [ { "email": "invalid@example.com", "name": "Invalid User" } ], "subject": "Welcome to Our Service", "emailType": "transactional", "ipID": 42, "ipPoolID": 7, "ipPool": "transactional-pool", "publicIP": "192.0.2.100", "headers": { "X-Campaign-Id": "12345" } } } ``` > [!NOTE] > > SMTP codes and descriptions are available in both the top-level `event` object and within `event.eventMetadata`. Both locations contain the same values for consistency and ease of access. *** ## Example: Opened Event with Full Metadata ```json theme={null} { "event": { "eventID": "evt-789gh-bfasdf-567egh", "type": 5, "messageID": "mjhl-1401-sasdf-129324", "submittedAt": 1704067200, "eventMetadata": { "userAgent": { "Family": "Chrome", "Major": "91", "Minor": "0", "Patch": "4472" }, "os": { "Family": "Mac OS X", "Major": "10", "Minor": "15", "Patch": "7" }, "device": { "Family": "Mac", "Brand": "Apple", "Model": "MacBook Pro" }, "geo": { "city": "San Francisco", "country": "United States", "countryCode": "US", "region": "California", "regionCode": "CA", "postalCode": "94102", "latitude": 37.7749, "longitude": -122.4194, "timezone": "America/Los_Angeles" }, "trackedIP": "203.0.113.42", "rawUserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" } }, "emailMessage": { "messageID": "mjhl-1401-sasdf-129324", "from": { "email": "support@example.com", "name": "Support Team" }, "to": [ { "email": "customer@example.com", "name": "John Doe" } ], "subject": "Welcome to Our Service", "emailType": "marketing", "ipID": 15, "ipPoolID": 3, "ipPool": "marketing-pool", "publicIP": "192.0.2.50", "headers": { "X-Campaign-Id": "summer-sale-2024", "X-Customer-Segment": "VIP" }, "groups": ["transactional", "welcome-series"] } } ``` *** ## Example: Clicked Event with URL ```json theme={null} { "event": { "eventID": "evt-101gh-cfasdf-890egh", "type": 6, "messageID": "mjhl-1401-sasdf-129324", "submittedAt": 1704067200, "eventMetadata": { "clickedURL": "https://example.com/products/summer-sale?utm_source=email&utm_campaign=summer-2024", "userAgent": { "Family": "Safari", "Major": "15", "Minor": "4" }, "os": { "Family": "iOS", "Major": "15", "Minor": "4" }, "device": { "Family": "iPhone", "Brand": "Apple", "Model": "iPhone 13" }, "geo": { "city": "New York", "country": "United States", "countryCode": "US", "region": "New York", "regionCode": "NY", "postalCode": "10001", "latitude": 40.7128, "longitude": -74.0060, "timezone": "America/New_York" }, "trackedIP": "198.51.100.78", "rawUserAgent": "Mozilla/5.0 (iPhone; CPU iPhone OS 15_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1" } }, "emailMessage": { "messageID": "mjhl-1401-sasdf-129324", "from": { "email": "marketing@example.com", "name": "Example Marketing" }, "to": [ { "email": "customer@example.com", "name": "Jane Smith" } ], "subject": "Don't Miss Our Summer Sale!", "emailType": "marketing", "ipID": 15, "ipPoolID": 3, "ipPool": "marketing-pool", "publicIP": "192.0.2.50", "headers": { "X-Campaign-Id": "summer-sale-2024", "X-Campaign-Type": "promotional" }, "groups": ["marketing", "summer-campaign"] } } ``` *** ## Custom Headers in Webhook Payloads Any custom headers you include in your email request are preserved and included in all webhook event payloads. This allows you to track campaigns, add custom identifiers, or pass metadata through the entire email lifecycle. ### How Headers are Preserved * **Included in All Events**: Custom headers sent in your email request are included in the `emailMessage.headers` object in **all** webhook events (Processed, Dropped, Delivered, Opened, Clicked, Bounced, Unsubscribed, Spam). * **Same Across Lifecycle**: The headers remain the same across all events for a given email message, allowing you to correlate events using your custom identifiers. * **Original Format**: Headers are returned exactly as you sent them in your email request. ### Example: Email Request with Custom Headers ```json theme={null} { "from": { "email": "support@example.com", "name": "Support Team" }, "to": [ { "email": "customer@example.com", "name": "John Doe" } ], "subject": "Order Confirmation", "htmlBody": "

    Thank you for your order!

    ", "headers": { "X-Campaign-Id": "summer-sale-2024", "X-Order-Id": "ORD-12345", "X-Customer-Segment": "VIP" } } ``` ### Example: Webhook Payload with Preserved Headers ```json theme={null} { "event": { "eventID": "edhg-123gh-afasdf-124egh", "type": 5, "messageID": "mjhl-1401-sasdf-129324", "submittedAt": 1704067200, "eventMetadata": { "userAgent": { "Family": "Chrome", "Major": "91" }, "os": { "Family": "Windows" } } }, "emailMessage": { "messageID": "mjhl-1401-sasdf-129324", "from": { "email": "support@example.com", "name": "Support Team" }, "to": [ { "email": "customer@example.com", "name": "John Doe" } ], "subject": "Order Confirmation", "emailType": "transactional", "ipID": 42, "ipPoolID": 7, "ipPool": "transactional-pool", "publicIP": "192.0.2.100", "headers": { "X-Campaign-Id": "summer-sale-2024", "X-Order-Id": "ORD-12345", "X-Customer-Segment": "VIP" }, "groups": ["transactional", "order-confirmation"] } } ``` ### Use Cases for Custom Headers **Campaign Tracking:** ```json theme={null} { "headers": { "X-Campaign-Id": "summer-sale-2024", "X-Campaign-Type": "promotional" } } ``` **Order/Transaction Tracking:** ```json theme={null} { "headers": { "X-Order-Id": "ORD-12345", "X-Transaction-Id": "TXN-67890" } } ``` **Customer Segmentation:** ```json theme={null} { "headers": { "X-Customer-Segment": "VIP", "X-Customer-Tier": "premium" } } ``` > [!NOTE] > > Custom headers are included in every webhook event for the email, allowing you to filter and process webhooks based on your custom identifiers or metadata. Note that at times your application may go down and as a result webhook API calls may fail. In such a scenario SendPost will attempt retry on the webhook for the next 10 hours before cancelling it forever. # Understanding Webhook Event Lifecycle Source: https://docs.sendpost.io/api-reference/webhook/understanding-webhook-event-lifecycle Learn about the complete email lifecycle and what each webhook event type means. Understand the difference between Processed and Sent events, and how delivery outcomes are determined. ## Email Lifecycle and Event Types When you use SendPost API to send an email, the message goes through a complete lifecycle with various events. Understanding each event type and its significance will help you track your email delivery and engagement effectively. ### Initial Processing Stage **1. Processed (Type 0)** * **What it means**: This is an acknowledgement that SendPost has successfully processed your email request and forwarded it to the SMTP machine for delivery. * **When it occurs**: Immediately after SendPost accepts your API request and validates the email. * **Significance**: This confirms that your email was accepted by SendPost and is queued for sending. It does not mean the email has been sent yet. **2. Dropped (Type 1)** * **What it means**: The email was dropped before delivery attempts were made. * **When it occurs**: If the email address is invalid, malformed, or exists in your suppression list. * **Significance**: No delivery attempt will be made. The email will not be sent to the recipient. **Validation (Type 82)** * **What it means**: The result of the real-time list cleaning check on the recipient address: `valid`, `invalid`, `catch all` or `unknown`. * **When it occurs**: Only for sub-accounts with the Real-Time List Cleaning add-on, and only on webhooks with Validation turned on. It usually arrives within seconds, before the delivery outcome. * **Significance**: An `invalid` email is not sent, and you also receive an SMTP Dropped (Type 26) or Dropped (Type 1) event for it. See [Real-Time Validation Results](/api-reference/webhook/validation-results). ### Delivery Stage After the email is processed, SendPost forwards it to the SMTP machine. When the SMTP machine actually sends the email, it will result in one of the following outcomes: **3. Delivered (Type 2)** * **What it means**: The email was successfully delivered to the recipient's mail server. * **When it occurs**: After the SMTP machine sends the email and receives a successful delivery confirmation from the recipient's mail server. * **Significance**: The email reached the recipient's mail server. Note: This does not guarantee the email reached the inbox (it could be in spam) or that the recipient has read it. **4. SoftBounced (Type 3)** * **What it means**: The recipient's mail server temporarily rejected the email (e.g., mailbox full, server temporarily unavailable). * **When it occurs**: When the recipient's mail server returns a temporary error code. * **Significance**: SendPost will automatically retry delivery for soft bounces. There can be a delay between when the email is sent and when the final outcome (Delivered, HardBounced, or remains SoftBounced) is determined due to these retry attempts. **5. HardBounced (Type 4)** * **What it means**: The recipient's mail server permanently rejected the email (e.g., invalid email address, domain doesn't exist). * **When it occurs**: When the recipient's mail server returns a permanent error code. * **Significance**: No further delivery attempts will be made. The email address gets added to your suppression list. > [!NOTE] > > **Important**: After the SMTP machine sends an email, you will receive exactly one of these four events: **Delivered**, **SoftBounced**, **HardBounced**, or **Dropped**. For soft bounces, there may be a delay between when the email is sent and when the final event is generated due to automatic retry attempts. ### Post-Delivery Engagement Stage Once an email has been delivered, recipients may interact with it, generating additional events: **6. Opened (Type 5)** * **What it means**: The recipient opened the email (requires open tracking to be enabled). * **When it occurs**: When the recipient opens the email and the tracking pixel is loaded. * **Significance**: Indicates engagement. Note: Some email clients block images by default, which may prevent open tracking. **7. Clicked (Type 6)** * **What it means**: The recipient clicked a link in the email (requires click tracking to be enabled). * **When it occurs**: When the recipient clicks a tracked link in the email. * **Significance**: Indicates strong engagement and interest in your content. **8. Unsubscribed (Type 7)** * **What it means**: The recipient clicked the unsubscribe link in your email. * **When it occurs**: When the recipient uses the unsubscribe link (typically the `{{unsubscribe}}` template variable). * **Significance**: The recipient will be automatically added to your suppression list and will not receive future emails. **9. Spam (Type 8)** * **What it means**: The recipient marked your email as spam. * **When it occurs**: When the recipient reports your email as spam through their email client. * **Significance**: This negatively impacts your sender reputation. The recipient will be added to your suppression list. ## Key Concepts ### Processed vs Sent * **Processed (Type 0)**: An acknowledgement that SendPost has processed your email request and forwarded it to the SMTP machine. This does not mean the email has been sent yet. * **Sent**: When the SMTP machine actually sends the email out. This happens after Processed, and you won't receive a separate "Sent" event. Instead, you'll receive one of the delivery outcome events (Delivered, SoftBounced, HardBounced, or Dropped). ### Delivery Outcomes After the SMTP machine sends an email, exactly one of these four events will be generated: 1. **Delivered**: Successfully delivered to the recipient's mail server 2. **SoftBounced**: Temporarily rejected (with automatic retries) 3. **HardBounced**: Permanently rejected (no further attempts) 4. **Dropped**: Dropped before delivery attempts (invalid address or in suppression list) ### Multiple Events Per Email For a single email message, multiple events can be generated throughout its lifecycle: * You'll always receive a **Processed** event * You'll receive exactly one delivery outcome event (**Delivered**, **SoftBounced**, **HardBounced**, or **Dropped**) * You may receive multiple engagement events (**Opened**, **Clicked**, **Unsubscribed**, **Spam**) if the recipient interacts with the email The `emailMessage` object in webhook payloads remains the same across all events, allowing you to correlate events using the `messageID`. > [!NOTE] > > For detailed information about the webhook payload structure, including SMTP codes and custom headers, see [SendPost Webhook Object](/api-reference/webhook/sendpost-webhook-object). # Update Webhook Source: https://docs.sendpost.io/api-reference/webhook/update-an-existing-webhook put /account/webhook/{webhook_id} Modify an existing webhook's configuration. Use this to change the endpoint URL or update which events trigger notifications. Send only the fields you want to change. Every field you leave out keeps its current value, so `{"enabled": false}` pauses the webhook without touching its URL or events. **What Can Be Updated:** - Webhook endpoint URL - Enabled/disabled events - Event-specific settings **Use Cases:** - Migrate to a new endpoint URL - Enable additional events as needs grow - Disable events to reduce traffic - Update after infrastructure changes # Real-Time Validation Results Source: https://docs.sendpost.io/api-reference/webhook/validation-results Receive the real-time list cleaning result for every email you send as a Validation webhook event (type 82), filter it by result, and skip the check for individual emails. If your sub-account has the **Real-Time List Cleaning** add-on, SendPost checks each recipient address before it sends the email. The Validation webhook event tells you the result for every email, so you know which addresses are good and don't need to check them again. > [!NOTE] > > Real-Time List Cleaning is an add-on. Contact support to turn it on for a sub-account. Without the add-on, no addresses are checked and no Validation events are sent. ## Turn it on Validation events go to your account-level webhooks, never to the per-email `webhookEndpoint`. * **Dashboard:** open **Webhooks**, edit or create a webhook, and tick **Validation**. * **API:** set `validated: true` when you [create](/api-reference/webhook/create-a-new-webhook) or [update](/api-reference/webhook/update-an-existing-webhook) a webhook. ```json theme={null} { "url": "https://example.com/webhooks/sendpost", "enabled": true, "validated": true } ``` An update that leaves out `validated` keeps its current value. To stop Validation events, send `"validated": false`. ## The results Each Validation event has `event.type` set to `82` and `event.validationStatus` set to one of four words: | `validationStatus` | What it means | Is the email sent? | | - | - | - | | `valid` | The recipient's mail server confirmed the mailbox, or SendPost has delivered to this address before. | Yes | | `invalid` | The mailbox or domain doesn't exist, or the address failed a check before the mailbox check (see below). | **No** | | `catch all` | The domain accepts mail for any address, so the mailbox can't be confirmed. | Yes | | `unknown` | The mail server gave a temporary or inconclusive answer, for example a full mailbox or a temporary block. | Yes | > [!NOTE] > > The value `catch all` contains a space. Match the four words exactly as shown. `event.smtpCode` and `event.smtpDescription` hold the mail server's reply, for example `550` and `5.1.1 The email account that you tried to reach does not exist`. A `catch all` result uses SendPost's own code `111` with the description `Catch all domain`. Free mailbox providers such as Gmail, Outlook and Yahoo are never reported as `catch all`. ### What happens to an invalid email An email whose address is `invalid` is not sent, and you also receive an event that says so: * **Rejected by the mailbox check:** you receive an **SMTP Dropped** event (type `26`), and the address is added to your suppression list. * **Stopped before the mailbox check:** if the domain is a known typo domain (for example `gmial.com`), the address already hard-bounced on SendPost, or it is on SendPost's blocklist, the email is dropped straight away. You receive a **Dropped** event (type `1`) and a Validation event with `invalid`, code `554` and the drop reason in `smtpDescription`. Addresses on your own suppression list are dropped without a check, so they get a **Dropped** event only, with no Validation event. ## Example payload ```json theme={null} { "event": { "eventID": "c1af52bc-d705-4199-b15f-4d257cddb81b", "type": 82, "messageID": "ded956e9-4c9e-4117-9e97-5c56315c63af", "accountID": 100, "subAccountID": 50441, "from": "notifications@example.com", "to": "no.such.user@example.org", "submittedAt": 1792141788568613635, "smtpCode": 550, "smtpDescription": "5.1.1 The email account that you tried to reach does not exist.", "validationStatus": "invalid" }, "emailMessage": { "messageID": "ded956e9-4c9e-4117-9e97-5c56315c63af", "from": { "email": "notifications@example.com", "name": "" }, "to": { "email": "no.such.user@example.org", "name": "" }, "headers": {} } } ``` `event.messageID` is the `messageId` returned when you sent the email, so you can match the result to the email and its other events. A Validation event is normally sent once per email and usually arrives within seconds of the send, before any Delivered event. In rare cases it can arrive twice, so de-duplicate on `messageID`. ## Choose which results you receive By default a webhook with Validation on receives all four results. To receive only some of them, set `eventSubOptions.validated` when you create or update the webhook, listing all four keys. A result set to `false`, or left out, is not sent. In the dashboard, use the checkboxes under **Filter validation results**. > [!WARNING] > > An update replaces all of `eventSubOptions`. If you also filter Dropped reasons with `eventSubOptions.dropped`, send both objects in the same update, or the one you leave out goes back to everything on. ```json theme={null} { "url": "https://example.com/webhooks/sendpost", "validated": true, "eventSubOptions": { "validated": { "valid": false, "invalid": true, "catchAll": true, "unknown": true } } } ``` ## Skip the check for one email If you already know an address is good, skip the check for that email. It is then sent without a check and gets no Validation event. Use either option: * **`skipValidation: true`** in the body of [Send Email](/api-reference/email/send-email) or [Send Email With Template](/api-reference/email/send-email-with-template). * **The header `X-Sendpost-Validate: false`** in `headers`. This also works over SMTP relay and in SDK versions that don't have `skipValidation` yet. ```json theme={null} { "from": { "email": "notifications@example.com" }, "to": [{ "email": "customer@example.com" }], "subject": "Your receipt", "htmlBody": "

    Thanks for your order.

    ", "skipValidation": true } ``` Both options can only turn the check off. They can't turn it on for a sub-account without the add-on. ## Test your endpoint In the dashboard, open a webhook, choose **Validation** as the test event and click **Test**. Your endpoint receives a type `82` event with `validationStatus` set to `valid` for `test@example.com`. Test events are always sent, whatever your Validation setting and filters are. # Webhook Signature Verification Source: https://docs.sendpost.io/api-reference/webhook/webhook-signature-verification SendPost signs a webhook request with HMAC-SHA256 when the webhook has a signing secret. Verify the signature to confirm that the request came from SendPost and that the payload hasn't been altered in transit. > [!WARNING] > > Webhooks are **not** signed with your Account API Key. Since May 2026 a webhook request is signed only when the webhook has its own secret; a webhook without a secret is delivered without signature headers. If your endpoint verifies signatures with your API key, set a secret on the webhook and verify with that secret instead. ## Set a Signing Secret You choose the secret. Use a long random value, for example the output of `openssl rand -hex 32`. * **Dashboard:** fill in **Webhook Secret (Optional)** when you create the webhook. The dashboard can't change the secret of an existing webhook; use the API for that. * **API:** send `secret` when you [create](/api-reference/webhook/create-a-new-webhook) or [update](/api-reference/webhook/update-an-existing-webhook) a webhook. On update, leaving `secret` out keeps the current secret, and `"secret": ""` removes it, so the webhook is delivered unsigned. Leading and trailing spaces are removed from the secret before it is stored. ### Changing the Secret Every delivery attempt, retries included, is signed with the secret the webhook has when the attempt is sent. A retry of an event from before the change therefore arrives signed with the new secret. To change the secret without rejecting requests: 1. Make your endpoint accept a signature computed with either the old or the new secret. 2. Set the new secret with [Update Webhook](/api-reference/webhook/update-an-existing-webhook). 3. Once requests verify with the new secret, remove the old one from your endpoint. ## Webhook Headers | Header | Sent | Description | | - | - | - | | `X-SendPost-Signature` | When the webhook has a secret | HMAC-SHA256 signature of the raw request body, keyed with the webhook's secret (hex-encoded) | | `X-SendPost-Signature-Alg` | When the webhook has a secret | Algorithm identifier (`hmac-sha256`) | | `X-SendPost-Webhook-Id` | Always | Unique webhook UUID for tracking | | `X-SendPost-Webhook-Attempt` | Always | Attempt number for retry tracking (useful for debugging) | ### Example Webhook Request Headers ``` X-SendPost-Signature: a1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456 X-SendPost-Signature-Alg: hmac-sha256 X-SendPost-Webhook-Id: 550e8400-e29b-41d4-a716-446655440000 X-SendPost-Webhook-Attempt: 1 ``` ## Verification Process To verify a webhook request: 1. **Extract the signature** from the `X-SendPost-Signature` header 2. **Read the raw request body** (as bytes/string, before any JSON parsing) 3. **Compute HMAC-SHA256** of the request body using the webhook's secret as the key 4. **Hex-encode** the computed signature 5. **Compare** the computed signature with the header value using a constant-time comparison If the signatures match, the webhook is authentic and unaltered. > [!WARNING] > > Always use constant-time comparison when comparing signatures to prevent timing attacks. Never use simple string equality (`==` or `===`). ## Code Examples Each example reads the webhook's secret from the `SENDPOST_WEBHOOK_SECRET` environment variable. ### JavaScript (Node.js) ```javascript theme={null} const crypto = require('crypto'); function verifyWebhookSignature(requestBody, signature, secret) { // Compute HMAC-SHA256 signature const computedSignature = crypto .createHmac('sha256', secret) .update(requestBody, 'utf8') .digest('hex'); const expected = Buffer.from(computedSignature, 'hex'); const received = Buffer.from(signature, 'hex'); // timingSafeEqual throws when the lengths differ if (expected.length !== received.length) { return false; } // Constant-time comparison return crypto.timingSafeEqual(expected, received); } // Express.js example app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => { const signature = req.headers['x-sendpost-signature']; const secret = process.env.SENDPOST_WEBHOOK_SECRET; // Your webhook's secret if (!signature) { return res.status(401).json({ error: 'Missing signature' }); } const isValid = verifyWebhookSignature( req.body.toString(), signature, secret ); if (!isValid) { return res.status(401).json({ error: 'Invalid signature' }); } // Parse JSON and process webhook const webhookData = JSON.parse(req.body); // ... process webhook data res.status(200).json({ received: true }); }); ``` ### Python ```python theme={null} import hmac import hashlib import os from flask import Flask, request, jsonify app = Flask(__name__) def verify_webhook_signature(request_body, signature, secret): """ Verify webhook signature using HMAC-SHA256. Args: request_body: Raw request body as bytes or string signature: Signature from X-SendPost-Signature header secret: Your webhook's secret Returns: bool: True if signature is valid, False otherwise """ # Ensure request_body is bytes if isinstance(request_body, str): request_body = request_body.encode('utf-8') # Compute HMAC-SHA256 signature computed_signature = hmac.new( secret.encode('utf-8'), request_body, hashlib.sha256 ).hexdigest() # Constant-time comparison return hmac.compare_digest(computed_signature, signature) @app.route('/webhook', methods=['POST']) def webhook_handler(): signature = request.headers.get('X-SendPost-Signature') secret = os.environ.get('SENDPOST_WEBHOOK_SECRET') # Your webhook's secret if not signature: return jsonify({'error': 'Missing signature'}), 401 # Get raw request body request_body = request.get_data() if not verify_webhook_signature(request_body, signature, secret): return jsonify({'error': 'Invalid signature'}), 401 # Parse JSON and process webhook webhook_data = request.get_json() # ... process webhook data return jsonify({'received': True}), 200 ``` ### Go ```go theme={null} package main import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "fmt" "io" "net/http" "os" ) func verifyWebhookSignature(body []byte, signature, secret string) bool { // Compute HMAC-SHA256 signature mac := hmac.New(sha256.New, []byte(secret)) mac.Write(body) computedSignature := hex.EncodeToString(mac.Sum(nil)) // Constant-time comparison return hmac.Equal([]byte(computedSignature), []byte(signature)) } func webhookHandler(w http.ResponseWriter, r *http.Request) { // Get signature from header signature := r.Header.Get("X-SendPost-Signature") if signature == "" { http.Error(w, "Missing signature", http.StatusUnauthorized) return } // Get the webhook's secret from environment secret := os.Getenv("SENDPOST_WEBHOOK_SECRET") if secret == "" { http.Error(w, "Webhook secret not configured", http.StatusInternalServerError) return } // Read raw request body body, err := io.ReadAll(r.Body) if err != nil { http.Error(w, "Failed to read body", http.StatusBadRequest) return } // Verify signature if !verifyWebhookSignature(body, signature, secret) { http.Error(w, "Invalid signature", http.StatusUnauthorized) return } // Parse JSON and process webhook // ... process webhook data w.WriteHeader(http.StatusOK) w.Write([]byte(`{"received": true}`)) } func main() { http.HandleFunc("/webhook", webhookHandler) http.ListenAndServe(":8080", nil) } ``` ### Ruby ```ruby theme={null} require 'sinatra' require 'openssl' require 'json' def secure_compare(a, b) return false unless a.bytesize == b.bytesize result = 0 a.bytes.zip(b.bytes) { |x, y| result |= x ^ y } result == 0 end def verify_webhook_signature(request_body, signature, secret) # Compute HMAC-SHA256 signature computed_signature = OpenSSL::HMAC.hexdigest( OpenSSL::Digest.new('sha256'), secret, request_body ) # Constant-time comparison secure_compare(computed_signature, signature) rescue false end post '/webhook' do signature = request.env['HTTP_X_SENDPOST_SIGNATURE'] secret = ENV['SENDPOST_WEBHOOK_SECRET'] # Your webhook's secret if signature.nil? || signature.empty? status 401 return { error: 'Missing signature' }.to_json end # Get raw request body request_body = request.body.read unless verify_webhook_signature(request_body, signature, secret) status 401 return { error: 'Invalid signature' }.to_json end # Parse JSON and process webhook webhook_data = JSON.parse(request_body) # ... process webhook data status 200 { received: true }.to_json end ``` ### Java (Spring Boot) ```java theme={null} import org.springframework.web.bind.annotation.*; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.HexFormat; @RestController public class WebhookController { private static final String ALGORITHM = "HmacSHA256"; @Value("${sendpost.webhook.secret}") private String webhookSecret; private boolean verifyWebhookSignature(byte[] body, String signature, String secret) { try { Mac mac = Mac.getInstance(ALGORITHM); SecretKeySpec secretKeySpec = new SecretKeySpec( secret.getBytes(StandardCharsets.UTF_8), ALGORITHM ); mac.init(secretKeySpec); byte[] computedSignature = mac.doFinal(body); String computedSignatureHex = HexFormat.of().formatHex(computedSignature); // Constant-time comparison return MessageDigest.isEqual( computedSignatureHex.getBytes(StandardCharsets.UTF_8), signature.getBytes(StandardCharsets.UTF_8) ); } catch (Exception e) { return false; } } @PostMapping("/webhook") public ResponseEntity handleWebhook( @RequestHeader(value = "X-SendPost-Signature", required = false) String signature, @RequestBody byte[] body) { if (signature == null || signature.isEmpty()) { return ResponseEntity.status(401).body(Map.of("error", "Missing signature")); } if (!verifyWebhookSignature(body, signature, webhookSecret)) { return ResponseEntity.status(401).body(Map.of("error", "Invalid signature")); } // Parse JSON and process webhook // String jsonBody = new String(body, StandardCharsets.UTF_8); // ... process webhook data return ResponseEntity.ok(Map.of("received", true)); } } ``` ### PHP ```php theme={null} 'Missing signature']); exit; } // Get raw request body $requestBody = file_get_contents('php://input'); if (!verifyWebhookSignature($requestBody, $signature, $secret)) { http_response_code(401); echo json_encode(['error' => 'Invalid signature']); exit; } // Parse JSON and process webhook $webhookData = json_decode($requestBody, true); // ... process webhook data http_response_code(200); echo json_encode(['received' => true]); ?> ``` ## Per-Email Webhook Endpoints [Send Email](/api-reference/email/send-email) and [Send Email With Template](/api-reference/email/send-email-with-template) accept a `webhookEndpoint`, a URL that receives the events of that one email. A `webhookEndpoint` can't carry a secret. A request to it is signed only when its URL exactly matches the URL of a webhook on your account that has a secret: same scheme, host, path, trailing slash and query string. To get signed requests on a `webhookEndpoint` URL: 1. Create an account webhook with exactly that URL and a secret. 2. Set `enabled: false` unless the URL should also receive events for all your other emails. A disabled webhook still supplies its secret. 3. Verify requests to that URL with that webhook's secret. A `webhookEndpoint` receives every event of its email except Validation, whatever events the matching webhook is set to receive. If the matching webhook is enabled, it also receives the email's events as an account webhook, so the URL gets those events twice. Use `event.eventID` to drop the duplicates. If the URL changes from email to email, use one account webhook with a secret instead, and route events on your side with the email's `groups` or the recipient's `customFields`. Both come back in the `emailMessage` part of each event. ## Important Considerations ### Request Body Handling > [!WARNING] > > **Critical**: Always use the **raw request body** (as bytes/string) for signature verification, not the parsed JSON object. The signature is computed on the exact bytes sent by SendPost. * **Do**: Read the raw body before parsing JSON * **Don't**: Parse JSON first and then try to verify the signature * **Do**: Preserve the exact byte sequence received * **Don't**: Modify, prettify, or re-encode the body ### Which Secret to Use Verify with the secret of the webhook the request was sent to. If your webhooks have different secrets, each one's requests are signed with its own. Your Account API Key and Sub-Account API Keys are never used for signing. ### Retry Attempts The `X-SendPost-Webhook-Attempt` header indicates which retry attempt this is. SendPost will retry failed webhook deliveries for up to 10 hours. Each retry will have the same payload but a different attempt number. ### Security Best Practices 1. **Set a secret on every webhook** and verify signatures before processing webhook data 2. **Use constant-time comparison** to prevent timing attacks 3. **Store your webhook secret securely** (environment variables, secret management services) 4. **Log verification failures** for security monitoring 5. **Reject requests without signatures** once the webhook has a secret ## Example Webhook Payload Here's an example of a webhook request with signature headers: **Headers:** ``` Content-Type: application/json X-SendPost-Signature: a1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456 X-SendPost-Signature-Alg: hmac-sha256 X-SendPost-Webhook-Id: 550e8400-e29b-41d4-a716-446655440000 X-SendPost-Webhook-Attempt: 1 ``` **Body:** ```json theme={null} { "event": { "eventID": "edhg-123gh-afasdf-124egh", "type": 5, "messageID": "mjhl-1401-sasdf-129324", "eventMetadata": { "userAgent": { "Family": "Chrome", "Major": "91" }, "os": { "Family": "Windows" } } }, "emailMessage": { "messageID": "mjhl-1401-sasdf-129324", "from": { "email": "support@example.com", "name": "Support Team" }, "to": [ { "email": "customer@example.com", "name": "John Doe" } ], "subject": "Welcome to Our Service" } } ``` The signature in `X-SendPost-Signature` is computed from the exact JSON body above using the webhook's secret. > [!NOTE] > > For more information about webhook events and payloads, see [SendPost Webhook Object](/api-reference/webhook/sendpost-webhook-object). # Webhook Reference Source: https://docs.sendpost.io/api-reference/webhook/webhook-testing Webhooks are a HTTP Post request made to your application endpoint when an interesting event happens at SendPost. This includes events such as email opens, clicks, hard bounce, spam, unsubscribe and more. You may want to consume webhook events if you want to replicate state of your email recipients to your internal system ( have they unsubcribed or has their email bounced ?) or you want to build custom analytics for internal product consumption. Other use-cases where consuming webhook may be relevant is when you are building an application on top of SendPost such as an email marketing software and you want to show emails delivered, opened, clicked etc. to your customers. ## Testing Webhooks Generally configuring a webhook is pretty cumbersome process for developers. At SendPost we have tried to make it a bit simpler: * **Webhook Single-Click Test** You can go to SendPost dashboard and click on button to test individual webhook. This will trigger a test Webhook API call of the specific event such as email open, click etc. * **Request Bin** [RequestBin](https://requestbin.com/) is a great service to inspect HTTP requests. You can create a temporary RequestBin URL and use the temporary URL as your webhook URL in SendPost. After that you can trigger webhook calls either using curl or through our Webhook Single-Click Test. RequestBin will then record the HTTP requests and allow you to inspect the HTTP requests to verify headers, JSON body, and other information about the webhook request. This will provide you with information about the HTTP requests used in the webhook if you don’t have a public URL set up yet and want to start developing right away. # Tracking & Analytics Source: https://docs.sendpost.io/guides/amazon-ses/analytics Track opens, clicks, bounces and configure rate limiting for Amazon SES emails in SendPost. ## Automatic Event Tracking Open and click tracking are automatically enabled in the "sendpost-events" configuration set that SendPost creates during setup. This means: * Opens are automatically tracked and reported as **SES Open** events (ID: 33) through SNS notifications * Clicks are automatically tracked and reported as **SES Click** events (ID: 34) through SNS notifications * View open and click rates in the SendPost dashboard *** ## Viewing Analytics 1. Navigate to **Stats** in your SendPost NavBar 2. Filter by: * **Provider**: Select your Amazon SES provider * **Event Type**: Filter specific SES events (27-36) * **Date Range**: Choose the time period * **Sub-account**: Filter by sub-account *** ## Automatic Webhook Configuration When you set up the Amazon SES integration, SendPost automatically: > [!TIP] > > Creates SNS topics for event notifications > [!TIP] > > Configures SNS subscriptions to SendPost webhook endpoints > [!TIP] > > Sets up the configuration set "sendpost-events" in Amazon SES with open and click tracking enabled > [!TIP] > > Configures the configuration set to publish all supported events to SNS **Events Configured**: * Processed (sent) * Delivered * Bounced (hard and soft) * Complaint (spam reports) * Rejected (dropped) * Opened (automatically tracked) * Clicked (automatically tracked) * Rendering Failure * Subscription/Unsubscribe > [!NOTE] > > All event notifications are delivered to SendPost via Amazon SNS, ensuring reliable event tracking and processing. *** ## Rate Limiting & Throttling ### Default Rate Limits By default, Amazon SES providers are configured with a rate limit of **100 emails per hour**. This limit is set at the provider level and applies to all emails sent through your Amazon SES integration. ### Configuring Rate Limits You can easily adjust the rate limit through the SendPost UI: **1. Navigate to Third party providers** Go to **Settings** → **Third party providers** in your SendPost Settings Menu **2. Edit Provider** Click on your Amazon SES provider's dropdown to edit its settings **3. Adjust Rate Limit** Update the **Max Sends Per Hour** value to match your Amazon SES sending limits or your desired sending rate **4. Save Changes** Save your changes. The new rate limit takes effect immediately. > [!NOTE] > > Rate limiting in SendPost is configured on an hourly basis. Adjust the hourly limit based on your Amazon SES account limits and sending requirements. Note that Amazon SES has its own sending limits that still apply. ### Provider-Level Throttling SendPost supports granular throttling for different email providers: | Provider | Description | | - | - | | Gmail | Throttle sending to Gmail addresses | | Yahoo | Throttle sending to Yahoo/AOL addresses | | Outlook | Throttle sending to Microsoft addresses | | Default | Throttle for all other domains | *** ## Next Steps * [Understand event types](/guides/amazon-ses/event-types) for detailed event information * [Troubleshoot issues](/guides/amazon-ses/troubleshooting) with analytics or rate limiting # Amazon SES Compatible API Source: https://docs.sendpost.io/guides/amazon-ses/compatible-api Migrate from Amazon SES with minimal code changes using SendPost's Amazon SES Compatible API. If you're currently using Amazon SES and want to migrate to SendPost, we offer **Amazon SES Compatible APIs** (v1 and v2) that minimize code changes. You only need to change the endpoint URL and replace AWS Signature authentication with a simple API key header. *** ## Quick Migration Steps **1. Change the endpoint URL** > [tab] SES v1 > > * From: `https://email.{region}.amazonaws.com/` > * To: `https://api.sendpost.io/api/v1/subaccount/email/ses/v1` > [tab] SES v2 > > * From: `https://email.{region}.amazonaws.com/v2/email/outbound-emails` > * To: `https://api.sendpost.io/api/v1/subaccount/email/ses/v2` **2. Update authentication** * From: AWS Signature Version 4 (complex signing with access/secret keys) * To: `X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY` header **3. Keep your request body** Use the exact same SES v1 or v2 JSON request format - no changes needed! **4. Optional: Add SendPostOptions** Optionally add `SendPostOptions` to leverage SendPost-specific features like IP Pool routing *** ## SES v1 Migration Example > [tab] Before (Amazon SES v1) > > ```bash theme={null} > curl -X POST "https://email.us-east-1.amazonaws.com/" \ > -H "Authorization: AWS4-HMAC-SHA256 Credential=..." \ > -H "Content-Type: application/x-amz-json-1.0" \ > -d '{ > "Source": "sender@example.com", > "Destination": { > "ToAddresses": ["recipient@example.com"] > }, > "Message": { > "Subject": { > "Data": "Hello World", > "Charset": "UTF-8" > }, > "Body": { > "Text": { > "Data": "Hello!", > "Charset": "UTF-8" > }, > "Html": { > "Data": "

    Hello!

    ", > "Charset": "UTF-8" > } > } > } > }' > ``` > [tab] After (SendPost SES v1) > > ```bash theme={null} > curl -X POST "https://api.sendpost.io/api/v1/subaccount/email/ses/v1" \ > -H "X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "Source": "sender@example.com", > "Destination": { > "ToAddresses": ["recipient@example.com"] > }, > "Message": { > "Subject": { > "Data": "Hello World", > "Charset": "UTF-8" > }, > "Body": { > "Text": { > "Data": "Hello!", > "Charset": "UTF-8" > }, > "Html": { > "Data": "

    Hello!

    ", > "Charset": "UTF-8" > } > } > }, > "SendPostOptions": { > "IPPool": "ses-pool" > } > }' > ``` *** ## SES v2 Migration Example > [tab] Before (Amazon SES v2) > > ```bash theme={null} > curl -X POST "https://email.us-east-1.amazonaws.com/v2/email/outbound-emails" \ > -H "Authorization: AWS4-HMAC-SHA256 Credential=..." \ > -H "Content-Type: application/x-amz-json-1.0" \ > -d '{ > "FromEmailAddress": "sender@example.com", > "Destination": { > "ToAddresses": ["recipient@example.com"] > }, > "Content": { > "Simple": { > "Subject": { > "Data": "Hello World", > "Charset": "UTF-8" > }, > "Body": { > "Text": { > "Data": "Hello!", > "Charset": "UTF-8" > }, > "Html": { > "Data": "

    Hello!

    ", > "Charset": "UTF-8" > } > } > } > } > }' > ``` > [tab] After (SendPost SES v2) > > ```bash theme={null} > curl -X POST "https://api.sendpost.io/api/v1/subaccount/email/ses/v2" \ > -H "X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "FromEmailAddress": "sender@example.com", > "Destination": { > "ToAddresses": ["recipient@example.com"] > }, > "Content": { > "Simple": { > "Subject": { > "Data": "Hello World", > "Charset": "UTF-8" > }, > "Body": { > "Text": { > "Data": "Hello!", > "Charset": "UTF-8" > }, > "Html": { > "Data": "

    Hello!

    ", > "Charset": "UTF-8" > } > } > } > }, > "SendPostOptions": { > "IPPool": "ses-pool" > } > }' > ``` *** ## Field Mappings ### SES v1 → SendPost | SES v1 Field | SendPost Field | Notes | | - | - | - | | `Source` | `From.Email`, `From.Name` | Supports "Name \" format | | `Destination.ToAddresses[]` | `To[].Email` | Direct mapping | | `Destination.CcAddresses[]` | `To[].Cc[]` | Direct mapping | | `Destination.BccAddresses[]` | `To[].Bcc[]` | Direct mapping | | `Message.Subject.Data` | `Subject` | Direct mapping | | `Message.Body.Text.Data` | `TextBody` | Direct mapping | | `Message.Body.Html.Data` | `HtmlBody` | Direct mapping | | `ReplyToAddresses[]` | `ReplyTo.Email` | First address only | | `Tags[]` | `Groups[]` | Formatted as "Name:Value" | | `SendPostOptions.IPPool` | `IPPool` | **SendPost extension** | | `SendPostOptions.TrackOpens` | `TrackOpens` | **SendPost extension** | | `SendPostOptions.TrackClicks` | `TrackClicks` | **SendPost extension** | | `SendPostOptions.WebhookEndpoint` | `WebhookEndpoint` | **SendPost extension** | ### SES v2 → SendPost | SES v2 Field | SendPost Field | Notes | | - | - | - | | `FromEmailAddress` | `From.Email`, `From.Name` | Supports "Name \" format | | `Destination.ToAddresses[]` | `To[].Email` | Direct mapping | | `Destination.CcAddresses[]` | `To[].Cc[]` | Direct mapping | | `Destination.BccAddresses[]` | `To[].Bcc[]` | Direct mapping | | `Content.Simple.Subject.Data` | `Subject` | Only `Simple` content type supported | | `Content.Simple.Body.Text.Data` | `TextBody` | Direct mapping | | `Content.Simple.Body.Html.Data` | `HtmlBody` | Direct mapping | | `ReplyToAddresses[]` | `ReplyTo.Email` | First address only | | `EmailTags[]` | `Groups[]` | Formatted as "Name:Value" | | `SendPostOptions.IPPool` | `IPPool` | **SendPost extension** | | `SendPostOptions.TrackOpens` | `TrackOpens` | **SendPost extension** | | `SendPostOptions.TrackClicks` | `TrackClicks` | **SendPost extension** | | `SendPostOptions.WebhookEndpoint` | `WebhookEndpoint` | **SendPost extension** | *** ## SendPostOptions Extension SendPost offers optional extensions through the `SendPostOptions` field that are not available in the standard SES API: ```json theme={null} { "SendPostOptions": { "IPPool": "ses-pool", // IP pool name for routing "TrackOpens": true, // Enable open tracking "TrackClicks": true, // Enable click tracking "WebhookEndpoint": "https://..." // Webhook URL for events } } ``` > [!NOTE] > > **Tracking Explained**: Open and click events are tracked via Amazon SES's configuration set ("sendpost-events") and delivered to SendPost through SNS notifications. The `TrackOpens` and `TrackClicks` options in `SendPostOptions` control SendPost's tracking pixels, which provide additional tracking when emails are processed by SendPost before being sent to SES. Both tracking methods work independently. *** ## Supported SES Features | Feature | SES v1 | SES v2 | Notes | | - | - | - | - | | `Source` / `FromEmailAddress` | ✅ | ✅ | Supports "Name \" format | | `Destination.ToAddresses` | ✅ | ✅ | Direct mapping | | `Destination.CcAddresses` | ✅ | ✅ | Direct mapping | | `Destination.BccAddresses` | ✅ | ✅ | Direct mapping | | `Message.Subject` / `Content.Simple.Subject` | ✅ | ✅ | Direct mapping | | `Message.Body.Text` / `Content.Simple.Body.Text` | ✅ | ✅ | Direct mapping | | `Message.Body.Html` / `Content.Simple.Body.Html` | ✅ | ✅ | Direct mapping | | `ReplyToAddresses` | ✅ | ✅ | First address only | | `Tags` / `EmailTags` | ✅ | ✅ | Mapped to Groups as "Name:Value" | | `SendPostOptions` | ✅ | ✅ | **SendPost extension** | *** ## Unsupported SES Features > [!WARNING] > > The following SES features are **not supported** and will return a `ValidationException` error if present: | Feature | Alternative | | - | - | | `RawMessage` (v1) | Use `Message` with `Subject` and `Body` instead | | `Content.Raw` (v2) | Use `Content.Simple` instead | | `Template`, `TemplateData`, `TemplateArn` (v1) | Use SendPost's native template API or include content directly | | `Content.Template` (v2) | Use SendPost's native template API or include content directly | | `SourceArn`, `ReturnPath`, `ReturnPathArn` (v1) | Handled automatically by SendPost | | `FromEmailAddressIdentityArn` (v2) | Not needed with SendPost | | `FeedbackForwardingEmailAddress` (v2) | Handled automatically by SendPost | | `ListManagementOptions` (v2) | Use SendPost's `{{unsubscribe}}` template variable | **Error Response for Unsupported Fields**: ```json theme={null} { "__type": "ValidationException", "message": "Field 'RawMessage' is not supported. Please use Message with Subject and Body instead." } ``` *** ## Response Format ### Success Response (HTTP 200) ```json theme={null} { "MessageId": "550e8400-e29b-41d4-a716-446655440000" } ``` ### Error Response (HTTP 400/403/413/429/500) ```json theme={null} { "__type": "ValidationException", "message": "1 validation error detected: Value at 'Source' failed to satisfy constraint: Member must satisfy regular expression pattern: [\\u0020-\\u007E]+" } ``` ### Error Types | Error Type | HTTP Status | Description | | - | - | - | | `ValidationException` | 400 | Invalid request format or missing required fields | | `AccessDeniedException` | 403 | Invalid or missing API key | | `MessageRejected` | 400 | Email rejected (e.g., domain not verified) | | `MailFromDomainNotVerifiedException` | 400 | Domain not verified in SendPost | | `MessageTooLarge` | 413 | Payload exceeds 10MB limit | | `TooManyRequestsException` | 429 | Rate limit exceeded | | `ServiceException` | 500 | Internal server error | *** ## Key Differences: SES v1 vs v2 | Feature | SES v1 | SES v2 | | - | - | - | | Source field | `Source` | `FromEmailAddress` | | Subject | `Message.Subject` | `Content.Simple.Subject` | | Body | `Message.Body` | `Content.Simple.Body` | | Tags | `Tags[]` | `EmailTags[]` | | Content types | Simple only | Simple, Raw, Template (only Simple supported) | *** ## IP Pool Routing When using the Amazon SES Compatible API, you can specify an IP Pool through `SendPostOptions.IPPool`. This IP Pool must be configured in SendPost to route traffic to your Amazon SES provider. > [!NOTE] > > **Important**: The IP Pool specified in `SendPostOptions.IPPool` must exist in SendPost and be configured to route to your Amazon SES provider. If not specified, the default IP Pool will be used. *** ## Next Steps * [Understand event types](/guides/amazon-ses/event-types) for tracking email status * [View analytics](/guides/amazon-ses/analytics) for your Amazon SES emails * [Troubleshoot issues](/guides/amazon-ses/troubleshooting) with the compatible API # Amazon SES Event Types Source: https://docs.sendpost.io/guides/amazon-ses/event-types Understand Amazon SES event types and how they map to SendPost for tracking email delivery and engagement. Amazon SES events are tracked with specific event type IDs in SendPost, allowing you to distinguish between native SendPost events and Amazon SES events. *** ## Amazon SES Event Types | Event Type | ID | Description | | - | - | - | | SES Processed | 27 | Email accepted by Amazon SES for delivery | | SES Delivered | 28 | Email successfully delivered to recipient | | SES Hard Bounced | 29 | Permanent delivery failure (invalid address, domain doesn't exist) | | SES Soft Bounced | 30 | Temporary delivery failure (mailbox full, temporarily blocked) | | SES Spam Report | 31 | Recipient marked email as spam (complaint event) | | SES Dropped | 32 | Email rejected by Amazon SES (invalid address, etc.) | | SES Open | 33 | Recipient opened the email (automatically tracked) | | SES Click | 34 | Recipient clicked a link (automatically tracked) | | SES Rendering Failure | 35 | Email rendering failure event | | SES Unsubscribe | 36 | Recipient unsubscribed | *** ## Bounce Type Details Amazon SES categorizes bounces into two types: > [accordion] Hard Bounce (ID: 29) > > Permanent failure (invalid email, domain doesn't exist). These addresses should be removed from your list. > [accordion] Soft Bounce (ID: 30) > > Temporary failure (mailbox full, temporarily blocked). Amazon SES may retry these automatically. Consider these as temporary issues. *** ## Event Data Each Amazon SES event includes: * Message ID (for correlation) * Recipient email * Timestamp * SMTP response code (for bounces) * User agent (for opens) * Clicked URL (for clicks) * SES-specific metadata *** ## Event Type Quick Reference | Event | ID | SES Event Name | | - | - | - | | Processed | 27 | `Send` | | Delivered | 28 | `Delivery` | | Hard Bounce | 29 | `Bounce` (permanent) | | Soft Bounce | 30 | `Bounce` (transient) | | Spam Report | 31 | `Complaint` | | Dropped | 32 | `Reject` | | Open | 33 | `Open` | | Click | 34 | `Click` | | Rendering Failure | 35 | `Rendering Failure` | | Unsubscribe | 36 | `Subscription` | *** ## Next Steps * [View analytics](/guides/amazon-ses/analytics) to see event statistics * [Troubleshoot issues](/guides/amazon-ses/troubleshooting) with event processing # Amazon SES Integration Source: https://docs.sendpost.io/guides/amazon-ses/overview Connect your Amazon SES account to SendPost for unified email management, advanced analytics, and enhanced deliverability monitoring. SendPost's Amazon SES integration allows you to use your existing Amazon SES account as a **Third-Party Sending Provider (TPSP)**. This means you can: * Send emails through Amazon SES while using SendPost's unified API * Receive and process Amazon SES events (opens, clicks, bounces, complaints, etc.) in SendPost * View all email analytics in one centralized dashboard * Apply SendPost's intelligent routing and throttling to your Amazon SES traffic * Automatically configure SES identities, configuration sets, and SNS notifications Additionally, SendPost offers **Amazon SES Compatible APIs (v1 and v2)** that allow you to migrate from Amazon SES with minimal code changes. *** ## Why Use Amazon SES with SendPost? | Feature | Amazon SES Alone | Amazon SES + SendPost | | - | - | - | | Multiple ESP management | ❌ | ✅ Unified dashboard for all providers | | Cross-provider analytics | ❌ | ✅ Compare performance across ESPs | | Advanced throttling | Basic | ✅ Per-provider rate limiting (Gmail, Yahoo, etc.) | | Failover routing | ❌ | ✅ Automatic fallback to other providers | | Centralized event logs | ❌ | ✅ All events in one place | | Sub-account management | Limited | ✅ Flexible sub-account hierarchy | | Automated SES setup | Manual | ✅ Automatic identity and config set creation | *** ## What's Covered in This Guide > [card] [Setting Up](/guides/amazon-ses/setup) > > Configure Amazon SES as a provider in SendPost with automatic identity and configuration set setup > [card] [Sending Emails](/guides/amazon-ses/sending-emails) > > Send emails through Amazon SES using the SendPost API with automatic IP Pool routing > [card] [Compatible API](/guides/amazon-ses/compatible-api) > > Migrate from Amazon SES with minimal code changes using our SES v1/v2 compatible APIs > [card] [Event Types](/guides/amazon-ses/event-types) > > Understand Amazon SES event types and how they map to SendPost > [card] [Analytics](/guides/amazon-ses/analytics) > > Track opens, clicks, bounces and configure rate limiting > [card] [Troubleshooting](/guides/amazon-ses/troubleshooting) > > Common issues, FAQs, and getting help *** ## Quick Reference ### Key Endpoints | Purpose | URL | | - | - | | Send Email (Native) | `POST /api/v1/subaccount/email/` | | Send Email (SES v1 Compatible) | `POST /api/v1/subaccount/email/ses/v1` | | Send Email (SES v2 Compatible) | `POST /api/v1/subaccount/email/ses/v2` | | View Events | SendPost Dashboard → Events | | View Analytics | SendPost Dashboard → Stats | ### Setup Checklist **1. Create AWS IAM User** Create IAM user with AmazonSESFullAccess and AmazonSNSFullAccess permissions **2. Add Provider** Add Amazon SES provider in SendPost dashboard with AWS credentials **3. Configure Sending Identities** Add domains or email addresses you want to send from **4. Setup Identities** Click "Setup Identities" to automatically configure SES **5. Add DNS Records** Add the generated DNS records to your domain's DNS settings **6. Test** Send a test email with the `ippool` parameter **7. Confirm Events** Confirm events appear in SendPost analytics # Sending Emails via Amazon SES Source: https://docs.sendpost.io/guides/amazon-ses/sending-emails Send emails through Amazon SES using the SendPost API with automatic IP Pool routing. Once your Amazon SES provider is configured and identities are set up, you can send emails through Amazon SES using the standard SendPost API. > [!NOTE] > > **Important**: You must include the `ippool` parameter in your API request to route emails through Amazon SES. Use the IP Pool that was automatically created for your SES integration. *** ## Basic Email Example ```bash theme={null} curl -X POST "https://api.sendpost.io/api/v1/subaccount/email/" \ -H "X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": { "email": "sender@yourdomain.com", "name": "Your Name" }, "to": [{ "email": "recipient@example.com", "name": "Recipient Name" }], "subject": "Hello from SendPost via Amazon SES", "htmlBody": "

    Hello!

    This email is sent through Amazon SES.

    ", "textBody": "Hello! This email is sent through Amazon SES.", "ippool": "ses-pool" }' ``` *** ## Email with Personalization ```bash theme={null} curl -X POST "https://api.sendpost.io/api/v1/subaccount/email/" \ -H "X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": { "email": "sender@yourdomain.com", "name": "Your Company" }, "to": [{ "email": "john@example.com", "name": "John Doe", "customFields": { "firstName": "John", "accountType": "Premium" } }], "subject": "Welcome {{firstName}}!", "htmlBody": "

    Welcome {{firstName}}!

    Your {{accountType}} account is ready.

    ", "ippool": "ses-pool" }' ``` > [!NOTE] > > **Automatic Tracking**: Open and click tracking are automatically enabled in the configuration set. You don't need to include `trackOpens` or `trackClicks` parameters in your API requests. > [!NOTE] > > **Domain Verification**: If you're routing emails only through Amazon SES (no SendPost IPs in your IP Pool), you don't need to verify your domain in SendPost. Your domain only needs to be verified in Amazon SES. However, if your IP Pool includes SendPost IPs alongside SES, the domain must be verified in both. *** ## Response **Success Response** (HTTP 200): ```json theme={null} [ { "messageId": "abc123-def456-ghi789", "errorCode": 0, "to": "recipient@example.com" } ] ``` *** ## Next Steps * [Migrate from Amazon SES](/guides/amazon-ses/compatible-api) using the Amazon SES Compatible API * [Understand event types](/guides/amazon-ses/event-types) for tracking email status * [View analytics](/guides/amazon-ses/analytics) for your Amazon SES emails * [Troubleshoot issues](/guides/amazon-ses/troubleshooting) if emails aren't sending # Setting Up Amazon SES Integration Source: https://docs.sendpost.io/guides/amazon-ses/setup Configure Amazon SES as a Third-Party Sending Provider in SendPost with automatic identity and configuration set setup. ## Prerequisites Before setting up the Amazon SES integration, ensure you have: ### 1. Amazon AWS Account * An active AWS account with Amazon SES enabled * Access to AWS IAM (Identity and Access Management) * SES account in a supported region (e.g., us-east-1, eu-west-1, ap-southeast-1) ### 2. AWS IAM Credentials To create IAM credentials for Amazon SES: **1. Log in to AWS Console** Log in to your [AWS Management Console](https://console.aws.amazon.com) **2. Navigate to IAM** Go to **IAM** → **Users** → **Create User** **3. Create IAM User** Create a new IAM user with programmatic access enabled **4. Attach Permissions** Attach the following IAM policies to the user: * **AmazonSESFullAccess**: Required for sending emails and managing SES resources * **AmazonSNSFullAccess**: Required for automatic webhook configuration via SNS **5. Save Credentials** Copy and securely store your **Access Key ID** and **Secret Access Key** (you won't be able to see the secret key again) > [!WARNING] > > **Important**: The IAM user must have both `AmazonSESFullAccess` and `AmazonSNSFullAccess` policies attached. Without these permissions, the automated setup will fail. ### 3. SendPost Account * A SendPost account with admin access * At least one sub-account created *** ## Setting Up Amazon SES Integration ### Step 1: Navigate to Third party providers 1. Log in to your [SendPost Dashboard](https://app.sendpost.io) 2. Go to **Settings** → **Third party providers** 3. Click the **NEW** button ### Step 2: Configure Amazon SES Provider 1. **Name**: Enter a descriptive name (e.g., "Production SES", "Marketing SES") 2. **Third Party Provider Type**: Select **Amazon SES** from the dropdown 3. **AWS Region**: Enter your AWS region (e.g., `us-east-1`, `eu-west-1`, `ap-southeast-1`) * This should match the region where your SES account is located 4. **AWS Access Key ID**: Paste your IAM user's Access Key ID 5. **AWS Secret Access Key**: Paste your IAM user's Secret Access Key 6. Click **Save** > [!NOTE] > > **Automated SES Setup**: SendPost will automatically configure Amazon SES by creating identities, setting up configuration sets for event tracking, and generating the required DNS records. Simply add these DNS records to your domain's DNS settings to complete verification. ### Step 3: Configure Sending Identities After saving the provider, you'll need to configure your sending identities: 1. **Add Sending Identities**: Enter the domains or email addresses you want to send emails from * You can add multiple identities (e.g., `example.com` or `noreply@example.com`) * These identities will be automatically created and configured in your Amazon SES account 2. **Domain Configuration Option**: Check **"Also configure domains in Sendpost"** if you want to: * Configure your domain in SendPost * Generate unified DNS records from both SES and SendPost * Allow your domain to send emails through both services > [!NOTE] > > **Domain Verification in SendPost**: If you're routing emails only through Amazon SES (no SendPost IPs in your IP Pool), you don't need to verify your domain in SendPost—your domain only needs to be verified in Amazon SES. However, if your IP Pool includes SendPost IPs alongside SES, the domain must be verified in both SendPost and Amazon SES. ### Step 4: Automated Setup Click the **"Setup Identities"** button to automatically configure Amazon SES. This will: > [!TIP] > > Create the required identities in Amazon SES > [!TIP] > > Set up configuration sets for event tracking (named "sendpost-events") > [!TIP] > > Configure SNS topics and subscriptions for webhook notifications > [!TIP] > > Generate the necessary DNS records for domain verification > [!TIP] > > Create an IP Pool in SendPost for this integration (automatically named) > [!TIP] > > Configure the domain in SendPost (if "Also configure domains in Sendpost" is enabled) > [!NOTE] > > **Important**: After the automated setup, you must add the generated DNS records to your domain's DNS settings to complete verification of identities and setting up Amazon SES integration. ### Step 5: Automatic IP Pool Creation When you set up the Amazon SES integration, SendPost **automatically creates an IP Pool** for this provider. This IP Pool is configured to route traffic to your Amazon SES provider. > [!NOTE] > > Unlike SendGrid, you don't need to manually create an IP Pool for Amazon SES. SendPost handles this automatically, making the setup process simpler. #### Configure IP Pool for Amazon SES Routing Even though the IP Pool is created automatically, you can review and fine-tune how traffic is routed through Amazon SES. #### Why IP Pools? IP Pools in SendPost allow you to control how your email traffic is distributed between SendPost's native infrastructure and third-party providers like Amazon SES. This enables: * **Volume-based routing**: Split your email volume between Amazon SES and SendPost infrastructure * **Easy traffic management**: Adjust the percentage of emails sent via Amazon SES vs SendPost at any time * **Gradual migration**: Start with a small percentage on Amazon SES and increase as needed * **Failover capability**: Route traffic to Amazon SES when SendPost IPs are warming up #### Setting Up IP Pool for Amazon SES **1. Review auto-created IP Pool** 1. Go to **Settings** → **IP Pools** in your SendPost dashboard 2. Locate the IP Pool that was automatically created for your Amazon SES provider 3. Open the IP Pool to review its routing configuration **2. Configure Routing** 1. In the IP Pool settings, ensure the routing is configured to use your Amazon SES provider 2. Optionally adjust the volume percentage you want to route through Amazon SES 3. You can easily adjust this percentage later to control traffic distribution **3. Optional: Create additional IP Pools** If you need separate routing for different use cases (e.g., transactional vs marketing), you can create additional IP Pools that also route to your Amazon SES provider. #### Volume-Based Routing You can configure what percentage of your email volume goes through Amazon SES vs SendPost's native infrastructure: | Configuration | Amazon SES | SendPost Infrastructure | | - | - | - | | 100% Amazon SES | All emails via Amazon SES | None | | 50/50 Split | 50% of emails | 50% of emails | | Amazon SES Backup | 0% (failover only) | 100% primary | > [!NOTE] > > You can change the volume distribution at any time through the SendPost UI without any code changes. **To find your IP Pool name**: 1. Go to **Settings** → **IP Pools** in your SendPost dashboard 2. Look for an IP Pool that corresponds to your Amazon SES provider 3. Use this IP Pool name in your API calls (see [Sending Emails via Amazon SES](/guides/amazon-ses/sending-emails)) *** ## Next Steps Once your Amazon SES integration is set up, you can: * [Send emails via Amazon SES](/guides/amazon-ses/sending-emails) using the SendPost API * [View analytics](/guides/amazon-ses/analytics) for your Amazon SES emails * [Understand event types](/guides/amazon-ses/event-types) for tracking email status # Troubleshooting & FAQs Source: https://docs.sendpost.io/guides/amazon-ses/troubleshooting Common issues, solutions, and frequently asked questions for Amazon SES integration with SendPost. ## Common Issues > [accordion] Emails Not Sending > > **Symptoms**: Emails are not being delivered through Amazon SES > > **Checklist**: > > * Verify your AWS credentials (Access Key ID and Secret Access Key) are valid > * Check that the IAM user has `AmazonSESFullAccess` and `AmazonSNSFullAccess` permissions > * Verify your AWS region matches your SES account region > * Check that the TPSP is active in SendPost > * Review the SendPost event logs for errors > * Confirm your Amazon SES account is in good standing and not in sandbox mode (if applicable) > * Verify your sending identities are verified in Amazon SES > > **Test Your AWS Credentials**: > > ```bash theme={null} > aws ses get-send-statistics --region us-east-1 \ > --aws-access-key-id YOUR_ACCESS_KEY_ID \ > --aws-secret-access-key YOUR_SECRET_ACCESS_KEY > ``` > > If this returns authentication errors, your credentials are invalid. > [accordion] Events Not Appearing > > **Symptoms**: Emails are sent but opens/clicks/bounces not showing > > **Checklist**: > > * Verify SNS topics and subscriptions are created in AWS Console > * Check that the configuration set "sendpost-events" exists in Amazon SES > * Ensure the configuration set is attached to your emails (automatically handled by SendPost) > * Verify SNS subscriptions are active and pointing to SendPost endpoints > * Wait a few minutes (events are processed asynchronously via SNS) > * Check AWS CloudWatch logs for SNS delivery errors > > **Verify Configuration Set in Amazon SES**: > > 1. Go to AWS Console → Amazon SES → Configuration Sets > 2. Confirm "sendpost-events" configuration set exists > 3. Verify event destinations are configured for SNS > [accordion] Bounces Not Processing > > **Symptoms**: Bounced emails not reflected in analytics > > **Check**: > > * Review SMTP codes in event details > * Hard bounces (ID: 29) = permanent failures > * Soft bounces (ID: 30) = temporary failures > * Ensure bounce events are enabled in the configuration set > * Verify SNS topic is receiving bounce notifications > [accordion] Identity Verification Issues > > **Symptoms**: Cannot send emails, identities not verified > > **Checklist**: > > * Verify DNS records are correctly added to your domain's DNS settings > * Wait for DNS propagation (can take up to 48 hours) > * Check identity verification status in Amazon SES console > * For email addresses, verify the verification email was clicked > * Ensure you're not in SES sandbox mode (if applicable, request production access) > > **Verify Identity in Amazon SES**: > > 1. Go to AWS Console → Amazon SES → Verified Identities > 2. Check verification status of your domain/email > 3. Review DNS records if domain verification is pending > [accordion] AWS Credential Errors > > | Error Code | Meaning | Solution | > | - | - | - | > | 401 | Invalid credentials | Regenerate Access Key ID and Secret Access Key in IAM | > | 403 | Insufficient permissions | Ensure IAM user has AmazonSESFullAccess and AmazonSNSFullAccess | > | 429 | Rate limit exceeded | Wait and retry, or increase limits in SendPost and AWS | > [accordion] SNS Configuration Issues > > **Symptoms**: Events not being received via SNS > > **Checklist**: > > * Verify SNS topics are created in the correct AWS region > * Check SNS subscription status (should be "Confirmed") > * Review SNS topic permissions (SendPost should have publish permissions) > * Check AWS CloudWatch logs for SNS delivery failures > * Verify the configuration set is publishing to the correct SNS topic > [accordion] Amazon SES Compatible API Errors > > **400 Bad Request with ValidationException**: > > ```json theme={null} > { > "__type": "ValidationException", > "message": "Field 'RawMessage' is not supported. Please use Message with Subject and Body instead." > } > ``` > > **Solution**: Remove the unsupported field from your request > > **403 AccessDeniedException**: > > ```json theme={null} > { > "__type": "AccessDeniedException", > "message": "Invalid or missing API key" > } > ``` > > **Solution**: Verify your `X-SubAccount-ApiKey` header is correct > > **413 MessageTooLarge**: > > ```json theme={null} > { > "__type": "MessageTooLarge", > "message": "Payload exceeds 10MB limit" > } > ``` > > **Solution**: Reduce request size below 10MB > > **429 TooManyRequestsException**: > > ```json theme={null} > { > "__type": "TooManyRequestsException", > "message": "Rate limit exceeded" > } > ``` > > **Solution**: Wait and retry, or increase rate limits *** ## Getting Help If you're still experiencing issues: 1. **Check Logs**: Review detailed event logs in SendPost dashboard 2. **Check AWS CloudWatch**: Review SNS and SES logs in AWS CloudWatch 3. **Contact Support**: Reach out to SendPost support with: * Your account ID * TPSP ID * Message ID (if available) * Error messages * Timestamp of the issue * AWS region and SES account status *** ## FAQs > [accordion] Can I use multiple Amazon SES accounts? > > Yes! Create a separate TPSP for each Amazon SES account. Each will have its own configuration set, SNS topics, and IP Pool. > [accordion] Does SendPost store my AWS credentials securely? > > Yes, all AWS credentials are encrypted at rest and never exposed in logs or API responses. > [accordion] Can I use Amazon SES for some emails and SendPost IPs for others? > > Yes, SendPost supports intelligent routing. You can configure rules to route specific traffic through Amazon SES using IP Pools. > [accordion] What happens if the SNS endpoint is temporarily unavailable? > > Amazon SNS will retry message delivery. Events will be processed once connectivity is restored. > [accordion] Do I need to manually create IP Pools? > > No! Unlike other providers, SendPost automatically creates an IP Pool for your Amazon SES integration. Just use the auto-created IP Pool name in your API calls. > [accordion] What is the configuration set name? > > SendPost automatically creates a configuration set named "sendpost-events" in your Amazon SES account. This configuration set is used for all event tracking. > [accordion] Can I gradually migrate traffic? > > Yes! You can run both systems in parallel during migration. Route a percentage of traffic to SendPost while keeping some on Amazon SES directly. > [accordion] What's the latency for event processing? > > Events are typically processed within 1-5 seconds of being received from Amazon SNS. > [accordion] Is there a limit on emails per day? > > SendPost doesn't impose hard limits, but your Amazon SES account limits still apply. Configure throttling to match your SES limits. > [accordion] What if I'm in Amazon SES sandbox mode? > > If your Amazon SES account is in sandbox mode, you can only send to verified email addresses. Request production access in the AWS Console to send to any email address. > [accordion] Can I use my existing SES configuration sets? > > SendPost uses its own configuration set ("sendpost-events") for event tracking. You can still use your existing configuration sets for other purposes, but SendPost emails will use the "sendpost-events" configuration set. > [accordion] Can I use the Amazon SES Compatible API without setting up a TPSP? > > No, you need to set up an Amazon SES provider (TPSP) in SendPost first. The compatible API routes emails through your configured SES provider. However, you can use the compatible API format even when sending through SendPost's native infrastructure by not specifying an IP Pool. > [accordion] Will my existing SES code work with SendPost? > > Yes! The Amazon SES Compatible API accepts the exact same request format as Amazon SES. You only need to change the endpoint URL and replace AWS Signature authentication with the `X-SubAccount-ApiKey` header. # Tracking & Analytics Source: https://docs.sendpost.io/guides/custom-smtp/analytics Track opens, clicks, bounces, and configure rate limiting for Custom SMTP emails in SendPost. Custom SMTP traffic is treated like any other TPSP in SendPost's analytics: same dashboard, same stat tables, and the same per-provider throttling (27 ISP categories). No special filtering is required. *** ## Open Tracking When `trackOpens` is enabled in your send request: * SendPost injects a tracking pixel pointing to SendPost's `/track/open` endpoint * Opens are recorded as **CS Open** events (ID: 65) * View open rates in the SendPost dashboard and events page *** ## Click Tracking When `trackClicks` is enabled: * SendPost rewrites links to SendPost's `/track/click` endpoint * Clicks are recorded as **CS Click** events (ID: 66) * View click rates and clicked URLs in the dashboard *** ## Unsubscribe Tracking Unsubscribe headers and links point to SendPost's `/track/unsubscribe` endpoint. Use the `{{unsubscribe}}` template variable or configure unsubscribe headers. Events are stored as **CS Unsubscribe** (ID: 68). *** ## Viewing Analytics 1. Go to **Analytics** (or **Events**) in your SendPost dashboard 2. Filter by: * **Provider**: Select your Custom SMTP provider * **Event Type**: Filter by CS event types (58–68) * **Date Range**: Choose the time period * **Sub-account**: Filter by sub-account Dashboard stats, domain reports, and mail reports aggregate Custom SMTP traffic the same way as other TPSPs. You can filter by TPSP type to compare Custom SMTP vs SendPost IPs or other providers. *** ## Rate Limiting & Throttling ### Default Rate Limit Custom SMTP TPSPs have a **Max Rate Per Hour** (default 100) set at creation. This is the global rate limit for this provider. You can change it in the provider settings. ### Per-Provider Throttling SendPost supports per-provider throttling across **27 ISP categories** (e.g., Gmail, Yahoo, Outlook). Custom SMTP uses the same provider-specific settings (stored in the same JSON columns as other TPSPs). You can set different hourly limits per provider (e.g., cap Gmail at 1,000/hour, others at 10,000/hour). Per-provider limits are configurable up to 100,000 messages per hour per provider. ### Configuring Rate Limits **1. Navigate to Providers** Go to **Settings** → **Providers** in your SendPost dashboard **2. Edit Custom SMTP Provider** Click your Custom SMTP provider to edit **3. Adjust Rate Limit** Update **Max Rate Per Hour** and any per-provider throttle settings **4. Save** Save; new limits take effect immediately *** ## Stats Synchronization Custom SMTP events update the same Redis counters and PostgreSQL stat tables as other TPSPs: * **tpspstat** – General TPSP stats per sub-account per provider * **tpspdomainstat** – TPSP stats per domain per sub-account per provider * **aggregatedtpspsmtpcodestat** – SMTP code aggregation for error analysis Background jobs sync these to Postgres every minute. No extra configuration is needed. *** ## Next Steps * [Event types](/guides/custom-smtp/event-types) for full list of CS events * [Troubleshooting](/guides/custom-smtp/troubleshooting) analytics or rate limiting # Event Reporting Agent Source: https://docs.sendpost.io/guides/custom-smtp/event-agent Install and configure the SendPost event reporting agent to report delivered, bounced, and deferred events from your MTA logs. The **event reporting agent** is a small program you install on the server where your MTA (e.g., Postfix) runs. It tails the MTA mail log, parses delivery status entries, correlates them to SendPost messages via `X-Sendpost-Message-UUID`, and batches events to SendPost's event ingestion API. This gives you **CSDelivered** and **CSHardBounced** / **CSSoftBounced** (from agent `delivered`, `bounced`, `soft_bounced`) in addition to synchronous **CSSent** and SendPost tracking events. The agent may also send `deferred`; SendPost accepts it but **does not store** deferred events (they do not appear in the UI). > [!NOTE] > > Agent failures do not cause message loss. If the agent is down, you still get CSSent (from SMTP 2xx) and open/click/unsubscribe tracking. The agent adds final delivery outcome (CSDelivered, etc.). *** ## Supported MTAs | MTA | Status | | - | - | | Postfix | Supported (initial release) | | PowerMTA, Haraka, others | Future releases | *** ## Installation ### One-Liner (Postfix) Run on the server where Postfix runs. Replace `` with the key from your Custom SMTP TPSP (shown once at creation). ```bash theme={null} curl -sSL https://sendpost-agent.s3.us-east-1.amazonaws.com/install.sh | sudo bash -s -- \ --api-key \ --mta postfix \ --endpoint https://api.sendpost.io/api/v1/tpsp/custom-smtp/events ``` The agent is distributed as a single statically-linked binary (\~10MB) and is installed as a systemd service with automatic restart on failure. ### Package Installation The agent is also available as: * `.deb` package (Debian/Ubuntu) * `.rpm` package (RHEL/CentOS) * Raw binary with shell installer Use the same `--api-key`, `--mta`, and `--endpoint` (or config file) as in the one-liner. *** ## Configuration Configuration can be provided via: * **Command-line flags** (as in the install command) * **Config file**: `/etc/sendpost-agent/config.yaml` | Option | Description | Default | | - | - | - | | `api-key` | Event Ingestion API Key (scoped to your Custom SMTP TPSP) | Required | | `mta` | MTA type | `postfix` | | `endpoint` | SendPost event ingestion URL | `https://api.sendpost.io/api/v1/tpsp/custom-smtp/events` | | `log-path` | Path to MTA mail log | `/var/log/mail.log` | Example `config.yaml`: ```yaml theme={null} api-key: "your-event-ingestion-api-key" mta: postfix endpoint: "https://api.sendpost.io/api/v1/tpsp/custom-smtp/events" log-path: "/var/log/mail.log" ``` *** ## What the Agent Reports (Postfix) The agent parses Postfix mail log entries and sends events with `event_type` one of: **delivered**, **bounced**, **deferred**, **soft\_bounced**. | Postfix status | Agent `event_type` | SendPost result | | - | - | - | | `status=sent` | `delivered` | CSDelivered (stored) | | `status=bounced` | `bounced` or `soft_bounced` | CSHardBounced or CSSoftBounced (SendPost classifies by SMTP description) | | `status=deferred` | `deferred` | Accepted but **not stored** (by design) | Each event can include SMTP response code and description. SendPost uses the SMTP description (keyword-based) to classify bounces as hard vs soft. Correlation to SendPost messages is done via **message\_id** (SendPost UUID) that Postfix logs when it receives the message. The agent maintains a mapping of Postfix queue ID → SendPost message UUID (with a 24-hour TTL for deferred retries). > [!WARNING] > > **Header preservation**: Your Postfix must preserve the `X-Sendpost-Message-UUID` header (or the header used for message-id correlation). Most default configurations do; if you use content\_filter or custom pipelines, ensure custom headers are not stripped. *** ## Batching and Resilience * **Batching**: Up to 100 events or 5 seconds, whichever comes first, then POST to the ingestion endpoint. * **Transient failures**: Exponential backoff (1s, 2s, 4s, 8s, up to 60s). * **Durability**: Unsent events are written to a local WAL file (max 100MB) at `/var/lib/sendpost-agent/pending.wal`. A cursor file at `/var/lib/sendpost-agent/cursor` tracks the last-read position in the mail log so the agent can resume after restart. *** ## Health and Monitoring | Endpoint | Purpose | | - | - | | `http://localhost:9113/health` | Health check | | `http://localhost:9113/metrics` | Prometheus metrics | Use these to monitor the agent from your existing monitoring stack. *** ## Request Payload (Event Ingestion API) **Endpoint**: `POST /api/v1/tpsp/custom-smtp/events`\ **Auth**: Header `X-SP-Event-ApiKey` (your Event Ingestion API Key). Missing or invalid → 401.\ **Rate limit**: 10,000 requests/minute per API key (when implemented). **Body** (JSON): ```json theme={null} { "events": [ { "message_id": "", "event_type": "delivered", "timestamp": "2026-02-19T12:00:00Z", "smtp_code": 250, "smtp_description": "OK", "recipient": "user@example.com" } ] } ``` * **message\_id** (required): SendPost message UUID. * **event\_type** (required): One of `delivered`, `bounced`, `deferred`, `soft_bounced`. * **timestamp** (optional): ISO 8601 (RFC3339). * **smtp\_code**, **smtp\_description**, **recipient** (optional). Validation: each event must have `message_id`; `event_type` must be in the allowed set; if present, `timestamp` must be RFC3339. Empty body or no events → 400. On success the API returns **200 OK** immediately; events are processed asynchronously. *** ## SendPost Side * The event ingestion endpoint authenticates requests with the **X-SP-Event-ApiKey** header (your Event Ingestion API Key). * On successful ingestion, SendPost updates the TPSP's **agent\_last\_seen\_at** timestamp. The dashboard shows ✓ when the agent has reported recently, or ⚠️ if it has not been seen or is stale. *** ## Next Steps * [Event types](/guides/custom-smtp/event-types) for CSDelivered, CSDeferred, CSHardBounced * [Troubleshooting](/guides/custom-smtp/troubleshooting) agent and event ingestion # Custom SMTP Event Types Source: https://docs.sendpost.io/guides/custom-smtp/event-types Understand Custom SMTP (CS) event types and how they map to the sending lifecycle. Custom SMTP events use the **CS** prefix and specific event type IDs in SendPost, so you can distinguish them from native SendPost and other TPSP events. *** ## Custom SMTP Event Types | Event Type | ID | Trigger | | - | - | - | | CSProcessed | 58 | SendPost accepted the message and queued it for relay to your SMTP server | | CSSent | 59 | Your MTA returned 2xx on relay (message accepted by your server for delivery) | | CSDelivered | 60 | Agent reports MTA `status=sent` (delivered to recipient's mail server) | | CSDeferred | 61 | Agent may send `deferred`; **accepted by API but not stored** (not shown in UI) | | CSDropped | 62 | Relay to your SMTP failed after all retries; or non-retryable pre-send failure (e.g. no verified return path domain, suppression, validation) | | CSHardBounced | 63 | Agent `bounced`/`soft_bounced` classified as hard (by SMTP description); or bounce processor (async DSN) | | CSSoftBounced | 64 | Agent `bounced`/`soft_bounced` classified as soft (by SMTP description); or bounce processor | | CSOpen | 65 | Recipient loaded the tracking pixel | | CSClick | 66 | Recipient clicked a tracked link | | CSSpamReport | 67 | FBL complaint (out of scope for initial release) | | CSUnsubscribe | 68 | Recipient used the unsubscribe link/header | *** ## Event Flow > [accordion] CSSent vs CSDelivered > > **CSSent** = Your MTA accepted the message from SendPost (synchronous SMTP 2xx response). > **CSDelivered** = Your MTA successfully delivered to the recipient's mail server (reported by the event agent from your MTA logs). > This mirrors SendPost's native model: Sent = accepted by sending infrastructure; Delivered = accepted by recipient's mail server. > [accordion] CSDropped > > Emitted when SendPost could not relay to your SMTP server after all retries (connection failure, timeout, or 4xx/5xx from your server). This is a relay failure, not a recipient bounce. CSHardBounced is only from the agent (MTA status=bounced) or the bounce processor (async DSN). > [accordion] Bounces: Agent vs Bounce Processor > > **Agent**: Sends `bounced` or `soft_bounced`; SendPost classifies each to CSHardBounced or CSSoftBounced using the SMTP description (keyword-based). **Bounce processor**: Receives async DSNs to `sp-bounce.{domain}` and emits CSHardBounced or CSSoftBounced when the original message was sent via Custom SMTP. > [accordion] CSDeferred not in UI > > The agent may send `deferred` events. SendPost accepts them but **does not store** deferred events (by design). CSDeferred (61) will not appear in the Events page or analytics. *** ## Event Sources Summary | Source | Events | | - | - | | SendPost queue | CSProcessed | | Synchronous SMTP response from your MTA | CSSent (2xx), CSDropped (after retries exhausted) | | Event reporting agent (MTA logs) | CSDelivered, CSHardBounced, CSSoftBounced (deferred accepted but not stored) | | SendPost tracking | CSOpen, CSClick, CSUnsubscribe | | Bounce processor | CSHardBounced, CSSoftBounced | *** ## Next Steps * [Event reporting agent](/guides/custom-smtp/event-agent) for CSDelivered, CSDeferred, CSHardBounced from your MTA * [Analytics](/guides/custom-smtp/analytics) to view event statistics * [Troubleshooting](/guides/custom-smtp/troubleshooting) event processing # Custom SMTP Integration Source: https://docs.sendpost.io/guides/custom-smtp/overview Connect your own SMTP server (Postfix or any standards-compliant MTA) to SendPost for unified analytics, routing, and throttling. SendPost's Custom SMTP integration allows you to use your **own SMTP server** as a **Third-Party Sending Provider (TPSP)**. This means you can: * Relay emails through your existing Postfix or other SMTP infrastructure * Receive full event visibility in SendPost (processed, sent, delivered, bounces, opens, clicks, unsubscribes) * Apply SendPost's per-provider throttling (27 ISP categories), IP pool routing, and retry logic * View all email analytics in one centralized dashboard alongside other providers No DNS changes are required. Your existing verified domain and bounce handling (`sp-bounce.{domain}`) are reused. SendPost prepares each message (DKIM, tracking pixel, click rewrites, headers) and relays it over SMTP to your server. Delivery events are captured via synchronous SMTP responses, SendPost tracking, the existing bounce processor, and an optional event reporting agent you install on your MTA. *** ## Why Use Custom SMTP with SendPost? | Feature | Your SMTP Alone | Custom SMTP + SendPost | | - | - | - | | Unified dashboard | ❌ | ✅ All events in one place | | Per-ISP throttling | Manual | ✅ Gmail, Yahoo, etc. (27 categories) | | IP pool routing | ❌ | ✅ Route % traffic through your MTA | | Retry & failover | Custom | ✅ Built-in retry logic, fallback to other providers | | Open/click tracking | Custom | ✅ SendPost tracking endpoints | | Bounce processing | Custom | ✅ Reuses SendPost bounce infrastructure | | Gradual migration | ❌ | ✅ Compare your MTA vs SendPost IPs side by side | *** ## What's Covered in This Guide > [card] [Setting Up](/guides/custom-smtp/setup) > > Create a Custom SMTP TPSP, verify connectivity, and install the event reporting agent > [card] [Sending Emails](/guides/custom-smtp/sending-emails) > > Send emails through your SMTP server using the SendPost API with IP Pool routing > [card] [Event Reporting Agent](/guides/custom-smtp/event-agent) > > Install and configure the agent to report delivered, bounced, and deferred events from your MTA logs > [card] [Event Types](/guides/custom-smtp/event-types) > > Understand CS event types and how they map to the sending lifecycle > [card] [Analytics](/guides/custom-smtp/analytics) > > Track opens, clicks, bounces, and configure rate limiting > [card] [Troubleshooting](/guides/custom-smtp/troubleshooting) > > Common issues, FAQs, and getting help *** ## Quick Reference ### Key Endpoints | Purpose | URL | | - | - | | Send Email | `POST /api/v1/subaccount/email/` | | Event Ingestion (agent) | `POST https://api.sendpost.io/api/v1/tpsp/custom-smtp/events` | | View Events | SendPost Dashboard → Events | ### Setup Checklist **1. Create Custom SMTP TPSP** In SendPost: Providers → NEW → Custom SMTP. Enter host, port, security, auth, and max rate. **2. Copy Event Ingestion API Key** Save the API key shown once after creation; it authenticates the event reporting agent. **3. Install Event Reporting Agent** Run the one-liner install on your MTA server (Postfix supported initially). **4. Configure IP Pool** Create an IP Pool in SendPost that routes traffic to your Custom SMTP TPSP. **5. Whitelist Domain** Use the same verified sending domain in SendPost that your MTA uses. **6. Send Test** Use the "Send Test" button in the UI or API with the IP pool to confirm the full pipeline. # Sending Emails via Custom SMTP Source: https://docs.sendpost.io/guides/custom-smtp/sending-emails Send emails through your own SMTP server using the SendPost API with IP Pool routing. Once your Custom SMTP provider and IP Pool are configured, you send emails through your SMTP server using the **same SendPost API** as for other providers. You must include the `ippool` parameter so traffic is routed to your Custom SMTP TPSP. > [!NOTE] > > **Important**: You must include the `ippool` parameter in your API request to route emails through your Custom SMTP server. SendPost prepares each message (DKIM, open pixel, click rewrites, unsubscribe headers, Return-Path, and SendPost metadata headers) and relays it over SMTP to your server. Your MTA receives a fully-formed, ready-to-deliver message. > [!WARNING] > > **Return path domain**: A verified return path domain is required for the sender domain. If none is configured, the message is not retried and SendPost emits **CSDropped** with reason "No verified return path domain configured for sender domain". *** ## Basic Email Example ```bash theme={null} curl -X POST "https://api.sendpost.io/api/v1/subaccount/email/" \ -H "X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": { "email": "sender@yourdomain.com", "name": "Your Name" }, "to": [{ "email": "recipient@example.com", "name": "Recipient Name" }], "subject": "Hello from SendPost via Custom SMTP", "htmlBody": "

    Hello!

    This email is relayed through your SMTP server.

    ", "textBody": "Hello! This email is relayed through your SMTP server.", "ippool": "custom-smtp-pool", "trackOpens": true, "trackClicks": true }' ``` *** ## Message Preparation (No Changes on Your Side) SendPost builds the message the same way as for its own infrastructure: * **DKIM**: Signed with your verified domain keys (when applicable) * **Open tracking**: Pixel pointing to SendPost `/track/tpsp/open/...` (events attributed as CSOpen) * **Click tracking**: Links rewritten to SendPost `/track/tpsp/click/...` (events attributed as CSClick) * **Unsubscribe**: Headers/links to SendPost `/track/tpsp/unsubscribe/...` (events attributed as CSUnsubscribe) * **Return-Path**: `bounces+{messageUUID}+{subAccountId}@sp-bounce.{verified-domain}` (reuses your existing bounce domain) * **Headers**: Including `X-Sendpost-Message-UUID`, `X-Sendpost-Account-ID`, `X-Sendpost-SubAccount-ID`, `X-Sendpost-TPSP-ID`, `X-Sendpost-TPSP-Type`, and others used for correlation and bounce attribution Your Postfix (or other MTA) can deliver the message as-is. The event reporting agent uses these headers to correlate log entries to SendPost messages. *** ## Response **Success Response** (HTTP 200): ```json theme={null} [ { "messageId": "abc123-def456-ghi789", "errorCode": 0, "to": "recipient@example.com" } ] ``` Relay to your SMTP server may still fail after accept (e.g., connection timeout, 4xx/5xx). SendPost retries up to 5 times with linear backoff. On success, you get **CSSent** when your MTA returns 2xx; **CSDropped** only if all retries fail. *** ## Next Steps * [Event types](/guides/custom-smtp/event-types) for CSProcessed, CSSent, CSDelivered, etc. * [Event reporting agent](/guides/custom-smtp/event-agent) for delivered/bounced/deferred from your MTA * [Analytics](/guides/custom-smtp/analytics) for opens, clicks, and throttling # Setting Up Custom SMTP Integration Source: https://docs.sendpost.io/guides/custom-smtp/setup Configure your own SMTP server as a Third-Party Sending Provider in SendPost with connectivity validation and event reporting. ## Prerequisites Before setting up the Custom SMTP integration, ensure you have: ### 1. SMTP Server * A running SMTP server (Postfix or any standards-compliant MTA) * Hostname or IP and port (e.g., 25, 465, 587, 2525) * Connection security: None, STARTTLS, or TLS * Authentication (if required): PLAIN or LOGIN; username and password > [!NOTE] > > OAuth or token-based SMTP auth is not supported. Only PLAIN/LOGIN and unauthenticated connections are supported. ### 2. SendPost Account * A SendPost account with admin access * At least one sub-account created * Your sending domain verified in SendPost (same domain your MTA uses) ### 3. Bounce Domain (Already Configured) Your verified domain should already have bounce handling: `sp-bounce.{domain}` CNAME'd to `sp.sendpost.info`. Custom SMTP reuses this; no additional DNS changes are required. *** ## Setting Up Custom SMTP Integration ### Step 1: Create Custom SMTP TPSP 1. Log in to your [SendPost Dashboard](https://app.sendpost.io) 2. Go to **Settings** → **Providers** 3. Click **NEW** and select **Custom SMTP** as the provider type ### Step 2: Configure SMTP Settings Fill in the form: | Field | Description | | - | - | | **Name** | A human-readable label (e.g., "Postfix Cluster US-East") | | **SMTP Host** | Hostname or IP of your SMTP server (e.g., `smtp.customer.com`) | | **SMTP Port** | Default 587; options include 25, 465, 587, 2525 | | **Connection Security** | None / STARTTLS / TLS | | **Authentication** | None / PLAIN / LOGIN | | **Username** | SMTP username (if auth is enabled) | | **Password** | SMTP password (if auth is enabled) | | **Max Rate Per Hour** | Global rate limit for this TPSP (default 60) | ### Step 3: Test Connection (Required) Before you can create the TPSP, you **must** click **Test Connection**. This runs a full SMTP connectivity test using the details you entered: > [!TIP] > > TCP dial → EHLO → STARTTLS (if configured) → AUTH (if configured) → MAIL FROM → RCPT TO → DATA (minimal test message) → QUIT * **If the test passes**: The **Submit** button is enabled. Click **Submit** to create the Custom SMTP TPSP. SendPost then creates the record, initializes per-provider hubs and consumers, and generates the Event Ingestion API Key. * **If the test fails**: A descriptive error is shown (e.g., connection refused, TLS handshake failed, auth rejected, MAIL FROM/RCPT TO/DATA failure, timeout). Fix your server or firewall, then run **Test Connection** again. Submit remains disabled until the test passes. > [!WARNING] > > **Save the Event Ingestion API Key** when it is displayed. It is shown only once and is required to install the event reporting agent. ### Step 4: Install Event Reporting Agent To get **delivered**, **bounced**, and **deferred** events from your MTA (in addition to synchronous **sent** and SendPost tracking), install the event reporting agent on the server where your MTA runs. The UI shows a one-liner install command. For Postfix: ```bash theme={null} curl -sSL https://sendpost-agent.s3.us-east-1.amazonaws.com/install.sh | sudo bash -s -- \ --api-key \ --mta postfix \ --endpoint https://api.sendpost.io/api/v1/tpsp/custom-smtp/events ``` Replace `` with the key from Step 3. The agent tails the Postfix mail log, parses delivery/bounce/defer entries, and batches them to SendPost's event ingestion endpoint. See [Event Reporting Agent](/guides/custom-smtp/event-agent) for configuration, log path, and health checks. ### Step 5: Configure IP Pool for Custom SMTP Routing 1. Go to **Settings** → **IP Pools** 2. Create a new IP Pool or edit an existing one 3. Configure routing so that traffic is sent to your Custom SMTP TPSP (e.g., set a percentage or use it as primary/failover) 4. Save. Use the pool name in API calls via the `ippool` parameter. ### Step 6: Send Test Email Use the **Send Test** button in the provider setup (or send via API with the correct `ippool`). Confirm: * **CSProcessed** – message queued * **CSSent** – your MTA returned 2xx (accepted for delivery) * **CSOpen** / **CSClick** – if tracking is enabled * **CSDelivered** – after the agent reports from your MTA logs (if agent is installed) *** ## Setup Checklist in UI After creation, the dashboard shows: * **SMTP connectivity**: ✓ (verified at creation) * **Agent status**: ✓ when `agent_last_seen_at` is recent, or ⚠️ if the agent has not reported yet or is stale *** ## Next Steps * [Send emails via Custom SMTP](/guides/custom-smtp/sending-emails) using the SendPost API * [Configure the event agent](/guides/custom-smtp/event-agent) for delivered/bounced/deferred events * [View event types](/guides/custom-smtp/event-types) and [analytics](/guides/custom-smtp/analytics) # Troubleshooting & FAQs Source: https://docs.sendpost.io/guides/custom-smtp/troubleshooting Common issues, solutions, and frequently asked questions for Custom SMTP integration with SendPost. ## Common Issues > [accordion] TPSP Creation Fails (SMTP Connectivity Test) > > **Symptoms**: "Connection refused", "TLS handshake failed", "Auth rejected", "MAIL FROM/RCPT TO/DATA failure", or "Timeout" when creating the Custom SMTP provider. > > **Checklist**: > > * Ensure the SMTP host and port are reachable from SendPost (firewall, security groups) > * For STARTTLS/TLS: verify certificate and that the server supports the chosen security > * For auth: confirm username/password are correct and the server accepts PLAIN or LOGIN > * Try connecting manually: `telnet smtp.yourhost.com 587` or `openssl s_client -connect smtp.yourhost.com:587 -starttls smtp` > > **Note**: At creation, SendPost runs a **full SMTP transaction** (EHLO, STARTTLS if configured, AUTH if configured, MAIL FROM, RCPT TO, DATA with minimal test message, QUIT). Any step can cause rejection. You can test without creating: `POST /api/v1/tpsp/test/custom-smtp` with the same SMTP config in the body. > [accordion] Emails Not Sending / CSDropped > > **Symptoms**: Messages show CSDropped or never reach your MTA. > > **Checklist**: > > * **No return path domain**: If CSDropped shows "No verified return path domain configured for sender domain", the sender domain has no verified return path; this is non-retryable. > * Confirm the IP Pool used in the request routes to your Custom SMTP TPSP > * Check that your SMTP server is up and accepting connections on the configured port > * Review CSDropped event details: SMTP code and description indicate relay failure (e.g., 5xx, connection timeout) > * Ensure rate limits (global and per-provider) are not exceeded > * Verify no suppression or validation rules are dropping the message before relay > > **Retry behavior**: SendPost retries up to 5 times with linear backoff (1h, 2h, 3h, 4h, 5h). CSDropped is emitted after all retries fail, or immediately for non-retryable failures (e.g. missing return path domain). > [accordion] Events Not Appearing (Agent) > > **Symptoms**: CSSent and opens/clicks appear, but CSDelivered / CSHardBounced / CSSoftBounced from the MTA do not. > > **Checklist**: > > * Confirm the event reporting agent is installed and running on the MTA server > * Verify the agent uses the correct Event Ingestion API Key (header `X-SP-Event-ApiKey`) > * Ensure each event has valid `message_id` (SendPost UUID) and `event_type` in `delivered`, `bounced`, `deferred`, `soft_bounced` > * Check agent config: correct log path (e.g. `/var/log/mail.log`), endpoint URL > * Ensure Postfix preserves headers (e.g. `X-Sendpost-Message-UUID`) so the agent can correlate queue ID → message UUID > * Check agent health: `http://localhost:9113/health` and logs for parse/connect errors > * In SendPost dashboard: "Agent status" should show ✓ when agent has reported recently > > **Note**: Deferred events are accepted by the API but **not stored** (by design); they will not appear in the UI. > [accordion] Bounces Not Reflected > > **Symptoms**: Recipient bounces not showing as CSHardBounced / CSSoftBounced. > > **Checklist**: > > * **Agent**: The agent sends `bounced` or `soft_bounced`; SendPost classifies to CSHardBounced vs CSSoftBounced using the SMTP description (keyword-based). Ensure the agent is running and includes `smtp_description` when available. > * **Bounce processor**: Async DSNs must go to your bounce address. Return-Path is `bounces+{uuid}+{said}@sp-bounce.{domain}`; ensure `sp-bounce.{domain}` CNAMEs to `sp.sendpost.info` and that your MTA sends bounces to that address. > * In Events, filter by CSHardBounced (63) and CSSoftBounced (64). > [accordion] Deferred not visible in UI > > By design, deferred events are **accepted by the event ingestion API but not stored**. They do not appear in the Events page or analytics. Only delivered, hard bounce, and soft bounce from the agent are stored. > [accordion] Agent Correlation Warnings > > **Symptoms**: Agent logs "unknown queue ID" or delivery entries not matching any message. > > **Causes**: Postfix queue ID rewritten (e.g. content\_filter), or custom headers stripped so message-id/UUID is lost. > > **Mitigation**: Preserve `X-Sendpost-Message-UUID` (or the header used for correlation) through your Postfix pipeline. Document required Postfix config in your runbook. *** ## Getting Help If issues persist: 1. **Events**: Use the SendPost Events page with filters (provider, event type, date) and note message IDs and timestamps. 2. **Support**: Contact SendPost support with: * Account ID and Custom SMTP TPSP ID * Message ID(s) and example timestamps * Error messages or SMTP codes from CSDropped/agent logs * Whether the agent is installed and agent\_last\_seen\_at recent *** ## FAQs > [accordion] Can I use multiple Custom SMTP servers? > > Yes. Create a separate Custom SMTP TPSP for each server. Each has its own Event Ingestion API Key and agent config. One TPSP maps to one SMTP server; for HA, put a load balancer in front of your MTAs. > [accordion] Is the Event Ingestion API Key the same as my SendPost API key? > > No. The Event Ingestion API Key is scoped only to that Custom SMTP TPSP and is used only to authenticate event submissions from the agent. It cannot send email or access other SendPost APIs. > [accordion] Does SendPost sign DKIM for Custom SMTP? > > SendPost prepares the message including DKIM signing (using your verified domain keys) before relaying to your SMTP server. Your MTA receives a fully-formed message. (Whether SendPost signs for Custom SMTP in all cases is product-specific; see PRD for current scope.) > [accordion] What if my SMTP server goes down? > > Messages stay in the queue and are retried (up to 5 times with backoff). If all retries fail, SendPost emits CSDropped. You are responsible for your MTA availability. > [accordion] Can I route some traffic to Custom SMTP and some to SendPost IPs? > > Yes. Use IP Pools: create a pool that routes a percentage to your Custom SMTP TPSP and the rest to SendPost IPs (or other TPSPs). Use the `ippool` parameter in the send API. > [accordion] Is the agent open source? > > The agent can be distributed as a binary; see product documentation for source availability. It is a single binary, runs as an unprivileged user, and only reads MTA logs (no write access to Postfix). > [accordion] How do I update the agent? > > Manual updates only. Re-run the install script or replace the binary and restart the service. > [accordion] Are duplicate events possible? > > SendPost may deduplicate terminal bounce events (e.g. agent and bounce processor both reporting). Non-terminal events (e.g. CSSent and CSDelivered) are distinct and both are stored. # Tracking & Analytics Source: https://docs.sendpost.io/guides/mailgun/analytics Track opens, clicks, bounces and configure rate limiting for Mailgun emails in SendPost. ## Open Tracking When `trackOpens` is enabled: * Mailgun inserts a tracking pixel into your HTML emails * Opens are tracked and reported as **MG Opened** events (ID: 54) * View open rates in the SendPost dashboard *** ## Click Tracking When `trackClicks` is enabled: * Mailgun rewrites links in your email to track clicks * Clicks are tracked and reported as **MG Clicked** events (ID: 55) * View click rates and URLs in the SendPost dashboard *** ## Viewing Analytics 1. Navigate to **Analytics** in your SendPost dashboard 2. Filter by: * **Provider**: Select your Mailgun provider * **Event Type**: Filter specific Mailgun events (48-57) * **Date Range**: Choose the time period * **Sub-account**: Filter by sub-account *** ## Rate Limiting & Throttling ### Default Rate Limits By default, Mailgun providers are configured with a rate limit of **100 emails per hour**. This limit is set at the provider level and applies to all emails sent through your Mailgun integration. ### Configuring Rate Limits You can easily adjust the rate limit through the SendPost UI: **1. Navigate to Providers** Go to **Settings** → **Providers** in your SendPost dashboard **2. Edit Provider** Click on your Mailgun provider to edit its settings **3. Adjust Rate Limit** Update the **Max Sends Per Hour** value to match your Mailgun plan limits or your desired sending rate **4. Save Changes** Save your changes. The new rate limit takes effect immediately. > [!NOTE] > > Rate limiting in SendPost is configured on an hourly basis. Adjust the hourly limit based on your Mailgun plan capacity and sending requirements. ### Provider-Level Throttling SendPost supports granular throttling for different email providers (27 total): | Provider | Description | | - | - | | Gmail | Throttle sending to Gmail addresses | | Yahoo | Throttle sending to Yahoo/AOL addresses | | Microsoft | Throttle sending to Outlook/Hotmail addresses | | iCloud | Throttle sending to iCloud addresses | | Comcast | Throttle sending to Comcast addresses | | Default | Throttle for all other domains | > [!NOTE] > > Each provider-specific throttle can be configured with its own settings for maximum concurrent connections, sends per minute, sends per hour, and sends per day. *** ## Next Steps * [Understand event types](/guides/mailgun/event-types) for detailed event information * [Troubleshoot issues](/guides/mailgun/troubleshooting) with analytics or rate limiting # Mailgun Event Types Source: https://docs.sendpost.io/guides/mailgun/event-types Understand Mailgun event types and how they map to SendPost for tracking email delivery and engagement. Mailgun events are tracked with specific event type IDs in SendPost, allowing you to distinguish between native SendPost events and Mailgun events. *** ## Mailgun Event Types | Event Type | ID | Mailgun Event | Description | | - | - | - | - | | MG Processed | 48 | (generated) | Email processed and sent to Mailgun | | MG Sent | 49 | `accepted` | Mailgun accepted the message for delivery | | MG Delivered | 50 | `delivered` | Email successfully delivered to recipient | | MG Hard Bounced | 51 | `failed` (severity: "permanent") | Permanent delivery failure | | MG Soft Bounced | 52 | `failed` (severity: "temporary") | Temporary delivery failure | | MG Dropped | 53 | `rejected` | Email rejected by Mailgun | | MG Opened | 54 | `opened` | Recipient opened the email | | MG Clicked | 55 | `clicked` | Recipient clicked a link | | MG Spam Report | 56 | `complained` | Recipient marked email as spam | | MG Unsubscribe | 57 | `unsubscribed` | Recipient unsubscribed | > [!NOTE] > > **MG Processed** (ID 48) is generated by SendPost when the message is successfully submitted to Mailgun, not from a webhook event. *** ## Bounce Type Details Mailgun categorizes bounces based on the `severity` field in the `failed` event: > [accordion] Hard Bounce (ID: 51) > > Permanent failure indicated by `severity: "permanent"`. This includes invalid email addresses, non-existent domains, or permanent rejections. These addresses should be removed from your list. > [accordion] Soft Bounce (ID: 52) > > Temporary failure indicated by `severity: "temporary"`. This includes full mailboxes, temporary server issues, or rate limiting. Mailgun may retry these automatically. *** ## Event Data Each Mailgun event includes: * Message ID (for correlation) * Recipient email * Timestamp * SMTP response code and message (for bounces) * User agent (for opens) * Client IP address (for opens/clicks) * Clicked URL (for clicks) * Mailgun-specific IDs *** ## Bounce Status Information Mailgun provides detailed delivery status in the `delivery-status` field: | Field | Description | | - | - | | `code` | SMTP response code (integer) | | `message` | SMTP response message (string) | **Example SMTP Codes**: | Code | Meaning | | - | - | | 250 | Success | | 421 | Service temporarily unavailable | | 450 | Mailbox temporarily unavailable | | 452 | Insufficient storage | | 550 | Mailbox unavailable (permanent) | | 551 | User not local | | 552 | Exceeded storage allocation | | 553 | Mailbox name invalid | | 554 | Transaction failed | *** ## Event Type Quick Reference | Event | ID | Mailgun Webhook Event | | - | - | - | | Processed | 48 | (generated internally) | | Sent | 49 | `accepted` | | Delivered | 50 | `delivered` | | Hard Bounce | 51 | `failed` (permanent) | | Soft Bounce | 52 | `failed` (temporary) | | Dropped | 53 | `rejected` | | Open | 54 | `opened` | | Click | 55 | `clicked` | | Spam | 56 | `complained` | | Unsubscribe | 57 | `unsubscribed` | *** ## Next Steps * [View analytics](/guides/mailgun/analytics) to see event statistics * [Troubleshoot issues](/guides/mailgun/troubleshooting) with event processing # Mailgun Integration Source: https://docs.sendpost.io/guides/mailgun/overview Connect your Mailgun account to SendPost for unified email management, advanced analytics, and enhanced deliverability monitoring. SendPost's Mailgun integration allows you to use your existing Mailgun account as a **Third-Party Sending Provider (TPSP)**. This means you can: * Send emails through Mailgun while using SendPost's unified API * Receive and process Mailgun events (opens, clicks, bounces, etc.) in SendPost * View all email analytics in one centralized dashboard * Apply SendPost's intelligent routing and throttling to your Mailgun traffic *** ## Why Use Mailgun with SendPost? | Feature | Mailgun Alone | Mailgun + SendPost | | - | - | - | | Multiple ESP management | ❌ | ✅ Unified dashboard for all providers | | Cross-provider analytics | ❌ | ✅ Compare performance across ESPs | | Advanced throttling | Basic | ✅ Per-provider rate limiting (Gmail, Yahoo, etc.) | | Failover routing | ❌ | ✅ Automatic fallback to other providers | | Centralized event logs | ❌ | ✅ All events in one place | | Sub-account management | Limited | ✅ Flexible sub-account hierarchy | *** ## What's Covered in This Guide > [card] [Setting Up](/guides/mailgun/setup) > > Configure Mailgun as a provider in SendPost with automatic webhook setup > [card] [Sending Emails](/guides/mailgun/sending-emails) > > Send emails through Mailgun using the SendPost API with IP Pool routing > [card] [Event Types](/guides/mailgun/event-types) > > Understand Mailgun event types and how they map to SendPost > [card] [Analytics](/guides/mailgun/analytics) > > Track opens, clicks, bounces and configure rate limiting > [card] [Troubleshooting](/guides/mailgun/troubleshooting) > > Common issues, FAQs, and getting help *** ## Quick Reference ### Key Endpoints | Purpose | URL | | - | - | | Send Email | `POST /api/v1/subaccount/email/` | | View Events | SendPost Dashboard → Events | ### Setup Checklist **1. Create Mailgun API Key** Create API key with full access permissions in your Mailgun account **2. Add Provider** Add Mailgun provider in SendPost dashboard with your API key and domain **3. Configure IP Pool** Create an IP Pool in SendPost configured to route traffic to Mailgun **4. Whitelist Domain** Whitelist your sending domain in SendPost (same domain used in Mailgun) **5. Test** Send a test email with the `ippool` parameter **6. Confirm Events** Confirm events appear in SendPost analytics # Sending Emails via Mailgun Source: https://docs.sendpost.io/guides/mailgun/sending-emails Send emails through Mailgun using the SendPost API with IP Pool routing. Once your Mailgun provider and IP Pool are configured, you can send emails through Mailgun using the standard SendPost API. > [!NOTE] > > **Important**: You must include the `ippool` parameter in your API request to route emails through Mailgun. *** ## Basic Email Example ```bash theme={null} curl -X POST "https://api.sendpost.io/api/v1/subaccount/email/" \ -H "X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": { "email": "sender@yourdomain.com", "name": "Your Name" }, "to": [{ "email": "recipient@example.com", "name": "Recipient Name" }], "subject": "Hello from SendPost via Mailgun", "htmlBody": "

    Hello!

    This email is sent through Mailgun.

    ", "textBody": "Hello! This email is sent through Mailgun.", "ippool": "mailgun-pool", "trackOpens": true, "trackClicks": true }' ``` *** ## Email with Personalization ```bash theme={null} curl -X POST "https://api.sendpost.io/api/v1/subaccount/email/" \ -H "X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": { "email": "sender@yourdomain.com", "name": "Your Company" }, "to": [{ "email": "john@example.com", "name": "John Doe", "customFields": { "firstName": "John", "accountType": "Premium" } }], "subject": "Welcome {{firstName}}!", "htmlBody": "

    Welcome {{firstName}}!

    Your {{accountType}} account is ready.

    ", "ippool": "mailgun-pool", "trackOpens": true, "trackClicks": true }' ``` *** ## Using Mailgun IP Pools If you have IP Pools configured in your Mailgun account, you can specify which Mailgun IP Pool to use via the `tpspIppool` parameter. > [!NOTE] > > The `tpspIppool` field is optional. Use it when you want to route emails through a specific IP Pool on the Mailgun side, separate from the SendPost IP Pool routing. **Parameters**: * `ippool`: The SendPost IP Pool that routes traffic to Mailgun (required) * `tpspIppool`: The IP Pool name configured in your Mailgun account (optional) ```bash theme={null} curl -X POST "https://api.sendpost.io/api/v1/subaccount/email/" \ -H "X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": { "email": "sender@yourdomain.com", "name": "Your Company" }, "to": [{ "email": "recipient@example.com", "name": "Recipient Name" }], "subject": "Hello from SendPost via Mailgun", "htmlBody": "

    Hello!

    This email is sent through a specific Mailgun IP Pool.

    ", "ippool": "mailgun-pool", "tpspIppool": "transactional", "trackOpens": true, "trackClicks": true }' ``` *** ## Using a Specific Mailgun IP Address If you have dedicated IPs in your Mailgun account, you can specify a specific IP address to use for sending via the `tpspIp` parameter. > [!WARNING] > > The IP address specified must be owned by your Mailgun account. This is different from IP pools which allow Mailgun to select an IP from a pool. **Parameters**: * `ippool`: The SendPost IP Pool that routes traffic to Mailgun (required) * `tpspIp`: The specific IP address owned by your Mailgun account (optional) ```bash theme={null} curl -X POST "https://api.sendpost.io/api/v1/subaccount/email/" \ -H "X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": { "email": "sender@yourdomain.com", "name": "Your Company" }, "to": [{ "email": "recipient@example.com", "name": "Recipient Name" }], "subject": "Hello from SendPost via Mailgun", "htmlBody": "

    Hello!

    This email is sent from a specific IP.

    ", "ippool": "mailgun-pool", "tpspIp": "192.0.2.1", "trackOpens": true, "trackClicks": true }' ``` *** ## Response **Success Response** (HTTP 200): ```json theme={null} [ { "messageId": "abc123-def456-ghi789", "errorCode": 0, "to": "recipient@example.com" } ] ``` *** ## Next Steps * [Understand event types](/guides/mailgun/event-types) for tracking email status * [View analytics](/guides/mailgun/analytics) for your Mailgun emails # Setting Up Mailgun Integration Source: https://docs.sendpost.io/guides/mailgun/setup Configure Mailgun as a Third-Party Sending Provider in SendPost with automatic webhook setup. ## Prerequisites Before setting up the Mailgun integration, ensure you have: ### 1. Mailgun Account * An active Mailgun account * A verified sending domain configured in Mailgun ### 2. Mailgun API Key To create an API key in Mailgun: **1. Log in to Mailgun** Log in to your [Mailgun Dashboard](https://app.mailgun.com) **2. Navigate to API Keys** Go to **Settings** → **API Security** → **API Keys** **3. Create API Key** Click **Create API Key** or use your existing primary API key **4. Set Permissions** Ensure the API key has full access permissions for: * **Sending**: Required for email delivery * **Webhooks**: Required for event tracking **5. Save Your Key** **Copy your API key** (you may not be able to see it again) ### 3. Mailgun Domain You'll need your Mailgun sending domain (e.g., `mg.yourdomain.com` or `yourdomain.com`). This is configured in Mailgun under **Sending** → **Domains**. ### 4. SendPost Account * A SendPost account with admin access * At least one sub-account created *** ## Setting Up Mailgun Integration ### Step 1: Navigate to Providers 1. Log in to your [SendPost Dashboard](https://app.sendpost.io) 2. Go to **Settings** → **Providers** (or navigate to the Providers page) 3. Click the **NEW** button ### Step 2: Configure Mailgun Provider 1. **Name**: Enter a descriptive name (e.g., "Production Mailgun", "Marketing Mailgun") 2. **Type**: Select **Mailgun** from the dropdown 3. **Key**: Paste your Mailgun API key 4. **Domain**: Enter your Mailgun sending domain (e.g., `mg.yourdomain.com`) 5. Click **Save** > [!NOTE] > > If you're using Mailgun's EU region, you may need to specify the EU API endpoint. Contact support for assistance with EU region configuration. ### Step 3: Automatic Webhook Configuration When you save the provider, SendPost automatically: > [!TIP] > > Registers webhooks with Mailgun for each event type > [!TIP] > > Configures all supported events for tracking > [!TIP] > > Creates the necessary processing infrastructure **Webhook URL Format**: `https://api.sendpost.io/tpsp/mailgun/account/{your-account-id}` **Events Configured**: * Accepted (sent) * Delivered * Failed (bounced) * Rejected * Opened * Clicked * Complained (spam reports) * Unsubscribed > [!NOTE] > > Mailgun requires a separate webhook registration for each event type, unlike other providers that use a single webhook. SendPost handles this automatically. ### Step 4: Configure IP Pool for Mailgun Routing Before sending emails via Mailgun, you need to configure an IP Pool in SendPost that routes traffic to your Mailgun provider. #### Why IP Pools? IP Pools in SendPost allow you to control how your email traffic is distributed between SendPost's native infrastructure and third-party providers like Mailgun. This enables: * **Volume-based routing**: Split your email volume between Mailgun and SendPost infrastructure * **Easy traffic management**: Adjust the percentage of emails sent via Mailgun vs SendPost at any time * **Gradual migration**: Start with a small percentage on Mailgun and increase as needed * **Failover capability**: Route traffic to Mailgun when SendPost IPs are warming up #### Setting Up IP Pool for Mailgun **1. Create IP Pool** 1. Go to **Settings** → **IP Pools** in your SendPost dashboard 2. Click **Create New IP Pool** 3. Enter a descriptive name (e.g., "mailgun-pool" or "transactional-mailgun") **2. Configure Routing** 1. In the IP Pool settings, configure the routing to use your Mailgun provider 2. Set the volume percentage you want to route through Mailgun 3. You can easily adjust this percentage later to control traffic distribution **3. Save Configuration** Save your IP Pool configuration. The pool name will be used in your API calls. #### Volume-Based Routing You can configure what percentage of your email volume goes through Mailgun vs SendPost's native infrastructure: | Configuration | Mailgun | SendPost Infrastructure | | - | - | - | | 100% Mailgun | All emails via Mailgun | None | | 50/50 Split | 50% of emails | 50% of emails | | Mailgun Backup | 0% (failover only) | 100% primary | > [!NOTE] > > You can change the volume distribution at any time through the SendPost UI without any code changes. ### Step 5: Whitelist Your Sending Domain You must whitelist the same sending domain in SendPost that you use in Mailgun. > [!WARNING] > > **Important**: The domain you use for sending emails (e.g., `yourdomain.com`) must be whitelisted in SendPost. This ensures proper email routing and deliverability. 1. Go to **Settings** → **Domains** in your SendPost dashboard 2. Click **Add Domain** 3. Enter the same domain you have configured in Mailgun (e.g., `yourdomain.com`) 4. Complete the domain verification process > [!NOTE] > > If you're using multiple sending domains in Mailgun, you need to whitelist each domain in SendPost. *** ## Next Steps Once your Mailgun integration is set up, you can: * [Send emails via Mailgun](/guides/mailgun/sending-emails) using the SendPost API * [Understand event types](/guides/mailgun/event-types) for tracking email status * [View analytics](/guides/mailgun/analytics) for your Mailgun emails # Troubleshooting & FAQs Source: https://docs.sendpost.io/guides/mailgun/troubleshooting Common issues, solutions, and frequently asked questions for Mailgun integration with SendPost. ## Common Issues > [accordion] Emails Not Sending > > **Symptoms**: Emails are not being delivered through Mailgun > > **Checklist**: > > * Verify your Mailgun API key is valid and has full access permissions > * Check that the Mailgun domain is correct and verified in your Mailgun account > * Ensure the TPSP is active in SendPost > * Review the SendPost event logs for errors > * Confirm your Mailgun account is in good standing > > **Test Your API Key**: > > ```bash theme={null} > curl -s --user 'api:YOUR_MAILGUN_API_KEY' \ > https://api.mailgun.net/v3/domains > ``` > > If this returns 401, your API key is invalid. > [accordion] Events Not Appearing > > **Symptoms**: Emails are sent but opens/clicks/bounces not showing > > **Checklist**: > > * Verify webhooks are registered in Mailgun Dashboard > * Check webhook URLs are correct for each event type > * Ensure webhook events are enabled > * Wait a few minutes (events are batched for processing) > > **Verify Webhooks in Mailgun**: > > 1. Go to Mailgun → Sending → Webhooks > 2. Confirm webhooks are configured for each event type > 3. Verify URLs show: `https://api.sendpost.io/tpsp/mailgun/account/{account-id}` > [accordion] Bounces Not Processing > > **Symptoms**: Bounced emails not reflected in analytics > > **Check**: > > * Review SMTP codes in event details > * Hard bounces (permanent severity) = permanent failures > * Soft bounces (temporary severity) = temporary failures > * Ensure bounce events (failed) are enabled in webhook settings > [accordion] API Key Errors > > | Error Code | Meaning | Solution | > | - | - | - | > | 401 | Unauthorized | Regenerate API key in Mailgun | > | 403 | Forbidden | Check API key permissions | > | 429 | Rate limit exceeded | Wait and retry, or increase limits | > | 400 | Bad Request | Check payload format, domain, or recipient format | > | 404 | Not Found | Verify domain is correct | > [accordion] Webhook Registration Issues > > **Symptoms**: Some or all webhooks not registered > > **Checklist**: > > * Check if webhooks appear in Mailgun dashboard > * Verify API key has webhook permissions > * Ensure SendPost API is accessible from Mailgun servers > * Try recreating the TPSP in SendPost > > **Note**: Mailgun requires a separate webhook for each event type. Some event types may fail to register independently. *** ## Getting Help If you're still experiencing issues: 1. **Check Logs**: Review detailed event logs in SendPost dashboard 2. **Contact Support**: Reach out to SendPost support with: * Your account ID * TPSP ID * Message ID (if available) * Error messages * Timestamp of the issue *** ## FAQs > [accordion] Can I use multiple Mailgun accounts? > > Yes! Create a separate TPSP for each Mailgun account. Each will have its own webhooks and configuration. > [accordion] Does SendPost store my Mailgun API key securely? > > Yes, all API keys are encrypted at rest and never exposed in logs or API responses. > [accordion] Can I use Mailgun for some emails and SendPost IPs for others? > > Yes, SendPost supports intelligent routing. You can configure IP Pools to route specific traffic through Mailgun and the rest through SendPost's native infrastructure. > [accordion] What happens if the webhook endpoint is temporarily unavailable? > > Mailgun will retry webhook delivery. Events will be processed once connectivity is restored. > [accordion] How do I use Mailgun's EU region? > > If your Mailgun account is in the EU region, you may need to configure the EU API endpoint. Contact SendPost support for assistance with EU region configuration. > [accordion] Can I specify which Mailgun IP Pool to use? > > Yes! Use the `tpspIppool` parameter in your API request to specify a Mailgun IP Pool, or use `tpspIp` to specify a specific IP address owned by your account. > [accordion] Can I gradually migrate traffic? > > Yes! You can run both systems in parallel during migration. Configure your SendPost IP Pool to route a percentage of traffic to Mailgun while keeping some on your current system. > [accordion] What's the latency for event processing? > > Events are typically processed within 1-5 seconds of being received from Mailgun. > [accordion] Is there a limit on emails per day? > > SendPost doesn't impose hard limits, but your Mailgun plan limits still apply. Configure throttling to match your Mailgun limits. > [accordion] How is Mailgun different from SendGrid/SparkPost integration? > > The main difference is that Mailgun requires a separate webhook registration for each event type, while SendGrid and SparkPost use a single webhook for all events. SendPost handles this automatically during setup. # Tracking & Analytics Source: https://docs.sendpost.io/guides/postmark/analytics Track opens, clicks, bounces, and configure rate limiting for Postmark emails in SendPost. ## Open Tracking When `trackOpens` is enabled: * Postmark inserts a tracking pixel into your template-rendered HTML * Opens are sent to the SendPost webhook and reported as **PM Open** events (ID: 75) * View open rates in the SendPost dashboard *** ## Click Tracking When `trackClicks` is enabled: * Postmark rewrites links to track clicks * Clicks are sent to the SendPost webhook and reported as **PM Click** events (ID: 76) * View click rates and URLs in the SendPost dashboard *** ## Viewing Analytics 1. Navigate to **Analytics** in your SendPost dashboard 2. Filter by: * **Provider**: Select your Postmark provider * **Event Type**: Filter by Postmark event types (69–78) * **Date Range**: Choose the time period * **Sub-account**: Filter by sub-account *** ## Rate Limiting & Throttling ### Default Rate Limits By default, Postmark providers are configured with a rate limit (e.g. **Max Sends Per Hour**). This limit is set at the provider level and applies to all emails sent through your Postmark integration. ### Configuring Rate Limits You can adjust the rate limit in the SendPost UI: **1. Navigate to Providers** Go to **Settings** → **Providers** in your SendPost dashboard **2. Edit Provider** Click on your Postmark provider to edit its settings **3. Adjust Rate Limit** Update the **Max Sends Per Hour** value to match your Postmark plan or desired sending rate **4. Save Changes** Save your changes. The new rate limit takes effect immediately. > [!NOTE] > > Rate limiting in SendPost is configured on an hourly basis. Set it according to your Postmark plan capacity and sending requirements. ### Provider-Level Throttling SendPost supports granular throttling by recipient domain: | Provider | Description | | - | - | | Gmail | Throttle sending to Gmail addresses | | Yahoo | Throttle sending to Yahoo/AOL addresses | | Outlook | Throttle sending to Microsoft addresses | | Default | Throttle for all other domains | *** ## Next Steps * [Understand event types](/guides/postmark/event-types) for full PM\* event list * [Troubleshoot](/guides/postmark/troubleshooting) analytics or rate limiting # Postmark Event Types Source: https://docs.sendpost.io/guides/postmark/event-types Understand Postmark event types and how they map to SendPost for tracking email delivery and engagement. Postmark events are tracked with specific event type IDs in SendPost (69–78), allowing you to distinguish them from native SendPost events and other TPSP events. *** ## Postmark Event Types | Event Type | ID | Source / RecordType | Description | | - | - | - | - | | PMProcessed | 69 | (generated on receive) | Acknowledgement that SendPost received your message | | PMSent | 70 | (generated on send) | Confirmation that the message was successfully sent to Postmark | | PMDelivered | 71 | Delivery | Delivered to recipient | | PMHardBounced | 72 | Bounce (HardBounce/TypeCode 1) | Permanent bounce | | PMSoftBounced | 73 | Bounce (other) | Transient/soft bounce | | PMDropped | 74 | (reserved) | — | | PMOpen | 75 | Open | Open tracking | | PMClick | 76 | Click | Link click | | PMSpamReport | 77 | SpamComplaint | Spam complaint | | PMUnsubscribe | 78 | (reserved) | — | *** ## How Events Are Received * **PMProcessed** (69): Acknowledgement that **SendPost received your message** (your API request was accepted). * **PMSent** (70): Confirmation that the **message was successfully sent to Postmark** (Postmark accepted it for delivery). * **All others**: Delivered by Postmark to the SendPost webhook URL `https://api.sendpost.io/tpsp/postmark/account/{accountId}`. The webhook is registered for the Message Stream you selected at provider setup and includes triggers for Open, Click, Delivery, Bounce, and Spam Complaint. *** ## Bounce Type Details Postmark categorizes bounces by `Type` or `TypeCode` in the webhook payload: > [accordion] Hard Bounce (ID: 72) > > Permanent failure (e.g. invalid address, domain doesn't exist). Mapped when Postmark sends `Type` = HardBounce or `TypeCode` = 1. These addresses should be removed from your list. > [accordion] Soft Bounce (ID: 73) > > Temporary or transient failure. Mapped for other bounce types. Postmark may retry; consider these as temporary issues. *** ## Event Data Each Postmark event processed by SendPost includes: * **Metadata** (from send): `accountId`, `tpspId`, `subAccountId`, `emailType`, `messageId`, `messageSubject` (used for attribution) * **RecordType**: Bounce, Delivery, Open, Click, SpamComplaint * **MessageID**, **MessageStream**, **Tag** * Record-type-specific fields (e.g. `Recipient`, `DeliveredAt` for Delivery; `UserAgent`, `OriginalLink`, `Geo` for Open/Click; bounce details for Bounce) *** ## Event Type Quick Reference | Event | ID | Meaning | | - | - | - | | Processed | 69 | SendPost received your message | | Sent | 70 | Message successfully sent to Postmark | | Delivered | 71 | `Delivery` (Postmark webhook) | | Hard Bounce | 72 | `Bounce` (HardBounce/TypeCode 1) | | Soft Bounce | 73 | `Bounce` (other) | | Open | 75 | `Open` | | Click | 76 | `Click` | | Spam Report | 77 | `SpamComplaint` | *** ## Next Steps * [View analytics](/guides/postmark/analytics) to see event statistics * [Troubleshoot](/guides/postmark/troubleshooting) event processing or webhooks # Postmark Integration Source: https://docs.sendpost.io/guides/postmark/overview Connect your Postmark account to SendPost for unified email management, template-based sending, and event tracking via Message Streams. SendPost's Postmark integration allows you to use your existing Postmark account as a **Third-Party Sending Provider (TPSP)**. This means you can: * Send emails through Postmark using SendPost's API with **templates** (Postmark Templates API) * Use a **Message Stream** of your choice (transactional, broadcast, etc.) configured at setup * Receive and process Postmark events (opens, clicks, deliveries, bounces, spam complaints) in SendPost * View all email analytics in one centralized dashboard * Apply SendPost's intelligent routing and throttling to your Postmark traffic *** ## Why Use Postmark with SendPost? | Feature | Postmark Alone | Postmark + SendPost | | - | - | - | | Multiple ESP management | ❌ | ✅ Unified dashboard for all providers | | Cross-provider analytics | ❌ | ✅ Compare performance across ESPs | | Advanced throttling | Basic | ✅ Per-provider rate limiting (Gmail, Yahoo, etc.) | | Failover routing | ❌ | ✅ Automatic fallback to other providers | | Centralized event logs | ❌ | ✅ All events in one place | | Sub-account management | Limited | ✅ Flexible sub-account hierarchy | *** ## What's Covered in This Guide > [card] [Setting Up](/guides/postmark/setup) > > Configure Postmark as a provider with Server API Token and Message Stream selection > [card] [Sending Emails](/guides/postmark/sending-emails) > > Send template-based emails through Postmark using the SendPost API > [card] [Event Types](/guides/postmark/event-types) > > Understand Postmark event types and how they map to SendPost > [card] [Analytics](/guides/postmark/analytics) > > Track opens, clicks, bounces, and configure rate limiting > [card] [Troubleshooting](/guides/postmark/troubleshooting) > > Common issues, FAQs, and getting help *** ## Quick Reference ### Key Endpoints | Purpose | URL | | - | - | | Send Email (Native) | `POST /api/v1/subaccount/email/` | | View Events | SendPost Dashboard → Events | ### Setup Checklist **1. Get Postmark Server API Token** Create or copy your Server API Token from Postmark **2. Add Provider** Add Postmark provider in SendPost (type: Postmark), enter token **3. Fetch and Select Message Stream** Click "Fetch message streams" and select one stream (e.g. outbound) **4. Use the auto-created IP Pool** An IP pool is auto-created when the provider is saved (100% to Postmark); find it via profile icon (top right) → IP Pools **5. Whitelist Domain (optional)** Optional: whitelist your sending domain in SendPost to enable domain-level stats for Postmark **6. Test** Send a test email with `ippool` and `tpspTemplate` (template required for Postmark) **7. Confirm Events** Confirm events appear in SendPost analytics (PM\* event types) # Sending Emails via Postmark Source: https://docs.sendpost.io/guides/postmark/sending-emails Send template-based emails through Postmark using the SendPost API with IP Pool routing and Postmark templates. Once your Postmark provider and IP Pool are configured, you can send emails through Postmark using the standard SendPost API. Postmark is used for **template-based sending** only: you must specify a Postmark template alias. > [!WARNING] > > **Important**: When routing to Postmark you must include: > > * **`ippool`** – The SendPost IP Pool that routes traffic to your Postmark provider > * **`tpspTemplate`** – The Postmark template alias (required; without it, send returns an error) *** ## Template-Based Sending (Required) Postmark sends via the [Send email with template](https://postmarkapp.com/developer/api/templates-api#email-with-template) API. The template alias is taken from the `tpspTemplate` parameter and passed to Postmark as `TemplateAlias`. Custom data for the template comes from your request's custom fields (e.g. `customFields` / template model). *** ## Basic Template Email Example ```bash theme={null} curl -X POST "https://api.sendpost.io/api/v1/subaccount/email/" \ -H "X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": { "email": "sender@yourdomain.com", "name": "Your Name" }, "to": [{ "email": "recipient@example.com", "name": "Recipient Name" }], "subject": "Hello from SendPost via Postmark", "ippool": "postmark-pool", "tpspTemplate": "welcome-template", "trackOpens": true, "trackClicks": true }' ``` * **`ippool`**: SendPost IP Pool configured to route to your Postmark provider * **`tpspTemplate`**: Postmark template alias (e.g. `welcome-template`) – **required** when sending via Postmark * **`customFields`**: Object passed to Postmark as `TemplateModel` (use empty `{}` if no variables) *** ## Template with Personalization (Template Model) Pass template variables via `customFields`; they are sent to Postmark as `TemplateModel`: ```bash theme={null} curl -X POST "https://api.sendpost.io/api/v1/subaccount/email/" \ -H "X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": { "email": "sender@yourdomain.com", "name": "Your Company" }, "to": [{ "email": "john@example.com", "name": "John Doe", "customFields": { "firstName": "John", "accountType": "Premium" } }], "subject": "Welcome {{firstName}}!", "ippool": "postmark-pool", "tpspTemplate": "welcome-template", "trackOpens": true, "trackClicks": true }' ``` Postmark will receive `TemplateModel` with these keys for use inside the template. *** ## Postmark Tag Postmark supports a single `Tag` per email for categorization in dashboards and reports. SendPost maps the **first** entry of the `groups` array on the send request to Postmark's `Tag`. * Pass `groups: ["transactional"]` to send `Tag: "transactional"` to Postmark * Postmark accepts only one tag per email — additional entries in `groups` are dropped silently * If `groups` is empty or omitted, no `Tag` is sent ```bash theme={null} curl -X POST "https://api.sendpost.io/api/v1/subaccount/email/" \ -H "X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": { "email": "sender@yourdomain.com", "name": "Your Company" }, "to": [{ "email": "recipient@example.com", "name": "Recipient Name" }], "subject": "Welcome!", "ippool": "postmark-pool", "tpspTemplate": "welcome-template", "groups": ["transactional"], "trackOpens": true, "trackClicks": true }' ``` The tag appears in Postmark's dashboard, in Postmark search, and on event payloads Postmark may send to your own webhooks. *** ## Custom Metadata Postmark supports custom metadata attached to each email; it is visible in the Postmark dashboard, in Postmark search, and is included in payloads delivered to your own Postmark webhooks. To attach custom metadata when sending via SendPost, add entries to the `headers` object in the request payload with keys prefixed by **`TPSP_METADATA_`** (case-insensitive). SendPost strips the prefix and forwards each key/value pair to Postmark as `Metadata`. The `TPSP_METADATA_*` entries are removed from the `Headers` array sent to Postmark and will **not** appear as MIME headers on the message Postmark relays. Other (non-prefixed) entries in `headers` continue to be passed to Postmark as regular MIME headers. For example, `"TPSP_METADATA_order_id": "ORD-78921"` in the payload becomes `Metadata: { "order_id": "ORD-78921" }` on Postmark, while `"X-Entity-Ref-ID": "ORD-78921"` is forwarded to Postmark as a regular MIME header on the email itself. ```bash theme={null} curl -X POST "https://api.sendpost.io/api/v1/subaccount/email/" \ -H "X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": { "email": "sender@yourdomain.com", "name": "Your Company" }, "to": [{ "email": "john@example.com", "name": "John Doe" }], "subject": "Your order #ORD-78921 is confirmed", "ippool": "postmark-pool", "tpspTemplate": "order-confirmation", "groups": ["transactional"], "headers": { "X-Entity-Ref-ID": "ORD-78921", "List-Unsubscribe": "", "TPSP_METADATA_order_id": "ORD-78921", "TPSP_METADATA_customer_id": "cus_42a91b", "TPSP_METADATA_plan_tier": "premium", "TPSP_METADATA_campaign": "spring-launch-2026" }, "trackOpens": true, "trackClicks": true }' ``` ### Reserved Keys The following keys are used by SendPost for webhook attribution and **cannot be overridden**. Entries like `TPSP_METADATA_accountId` are dropped silently: * `accountId` * `tpspId` * `subAccountId` * `emailType` * `messageId` * `messageSubject` > [!NOTE] > > The customer's casing on the stripped key is preserved — Postmark accepts mixed-case keys, and SendPost does not normalize them. `TPSP_METADATA_OrderId` is sent to Postmark as `OrderId`, not `orderid`. ### Limits Postmark enforces the following limits. SendPost applies them before sending and **drops any entry that violates a limit** — the send still succeeds for the remaining metadata. | Limit | Value | | - | - | | Maximum keys per email | 25 | | Maximum key length (after the `TPSP_METADATA_` prefix is stripped) | 50 characters | | Maximum value length | 200 characters | ### Visibility > [!NOTE] > > Custom metadata is visible in the **Postmark dashboard**, in **Postmark search**, and on payloads Postmark delivers to your own webhooks. SendPost does **not** store custom metadata in its analytics — it is not surfaced in SendPost events or dashboards. *** ## Optional Parameters | Parameter | Description | | - | - | | `replyTo` | Reply-to address (optional) | | `cc` / `bcc` | Cc and Bcc recipients (optional) | | `groups` | First entry is sent as Postmark's `Tag` (see [Postmark Tag](#postmark-tag)) | | `headers` | Custom headers object; sent as `Headers` array to Postmark. Entries with keys prefixed `TPSP_METADATA_` are stripped and routed to Postmark's `Metadata` instead (see [Custom Metadata](#custom-metadata)) | | `trackOpens` | Enable open tracking (default: as configured) | | `trackClicks` | Enable click tracking; maps to `TrackLinks`: "HtmlAndText" or "HtmlOnly" | SendPost also sends metadata (e.g. `accountId`, `tpspId`, `subAccountId`, `emailType`, `messageId`, `messageSubject`) to Postmark for webhook attribution; you do not need to set these manually. *** ## Message Stream The **Message Stream** used for sending is the one you selected when creating the Postmark provider in SendPost. It is stored with the TPSP and sent with every request to Postmark; you do not pass it in each API call. The same stream is used for the webhook registered at setup. *** ## Response **Success Response** (HTTP 200): ```json theme={null} [ { "messageId": "abc123-def456-ghi789", "errorCode": 0, "to": "recipient@example.com" } ] ``` On success, Postmark accepts the message and SendPost records a **PMProcessed** (ID: 69) event. Delivery, opens, clicks, bounces, and spam complaints are reported via webhooks and appear as PM\* event types in SendPost. **Retries**: SendPost retries on 429 (rate limit) and 5xx from Postmark. On 4xx (except 429), no retry is performed. *** ## Next Steps * [Understand event types](/guides/postmark/event-types) for PMProcessed, PMDelivered, PMOpen, etc. * [View analytics](/guides/postmark/analytics) for your Postmark emails * [Troubleshoot](/guides/postmark/troubleshooting) sending or template errors # Setting Up Postmark Integration Source: https://docs.sendpost.io/guides/postmark/setup Configure Postmark as a Third-Party Sending Provider in SendPost with Server API Token and Message Stream selection. ## Prerequisites Before setting up the Postmark integration, ensure you have: ### 1. Postmark Account * An active Postmark account * A **Server API Token** (single credential; no domain required for TPSP setup) ### 2. Postmark Server API Token To get your Server API Token in Postmark: **1. Log in to Postmark** Log in to your [Postmark Dashboard](https://account.postmarkapp.com) **2. Select Server** Select the server you want to use for sending **3. Get API Token** Go to **API Tokens** (or Server → API Tokens) and copy your **Server API token** **4. Save Your Token** **Copy your Server API token** and keep it secure (you may use it only for this SendPost provider) ### 3. SendPost Account * A SendPost account with admin access * At least one sub-account created *** ## Setting Up Postmark Integration ### Step 1: Navigate to Providers 1. Log in to your [SendPost Dashboard](https://app.sendpost.io) 2. Go to **Settings** → **Providers** (or navigate to the Providers page) 3. Click the **NEW** button ### Step 2: Configure Postmark Provider 1. **Name**: Enter a descriptive name (e.g., "Production Postmark", "Transactional Postmark") 2. **Type**: Select **Postmark** from the dropdown (provider type 4) 3. **Key**: Paste your Postmark **Server API Token** 4. Click **Fetch message streams** to load your Postmark message streams (SendPost calls the Postmark API with your token) 5. **Message Stream**: Select one message stream from the dropdown (e.g. "outbound", or a custom stream). The value is the stream ID; the display shows the stream name and type. 6. Submit is disabled until a message stream is selected. 7. Click **Save** > [!WARNING] > > **Required**: You must select a **Message Stream** before saving. Postmark requires a stream for both sending and webhook registration. Without it, the provider cannot be created. > [!NOTE] > > No domain is required at the provider level for Postmark. Your sending domain is still whitelisted in SendPost for deliverability; the Postmark side uses the From address you supply when sending. ### Step 3: Automatic Webhook Configuration When you save the provider, SendPost automatically: > [!TIP] > > Registers one webhook with Postmark for the selected Message Stream > [!TIP] > > Configures triggers: Open, Click, Delivery, Bounce, Spam Complaint **Webhook URL Format**: `https://api.sendpost.io/tpsp/postmark/account/{your-account-id}` **Events Configured**: * Open (first and subsequent) * Click * Delivery * Bounce (hard and soft) * Spam Complaint Postmark allows one webhook per stream with multiple triggers; SendPost uses that single webhook for all supported events. ### Step 4: Use the Auto-Created IP Pool When you save the Postmark provider, SendPost **automatically creates** an IP pool for that provider. This pool is configured to route **100% of its volume** to Postmark—no manual setup needed. **Finding your IP pool**: Click the **profile icon** (top right) → **IP Pools**. The pool created for your Postmark provider appears there. Use its name as the `ippool` parameter in your API calls when sending via Postmark. ### Step 5: Whitelist Your Sending Domain (Optional) Whitelisting your sending domain in SendPost is **optional**. If the IP pool you use only sends volume to Postmark, you can skip this step and start sending. > [!WARNING] > > **If you skip this step**: SendPost will not be able to show you **domain-level stats** for Postmark (e.g. per-domain opens, bounces, clicks). Subaccount and provider-level stats will still be available. To enable domain-level stats for Postmark: 1. Go to **Settings** → **Domains** in your SendPost dashboard 2. Click **Add Domain** 3. Enter the domain you use in your From address (e.g., `yourdomain.com`) 4. Complete the domain verification process *** ## Next Steps Once your Postmark integration is set up, you can: * [Send emails via Postmark](/guides/postmark/sending-emails) using the SendPost API (with `ippool` and `tpspTemplate`) * [View event types](/guides/postmark/event-types) for Postmark (PM\* events) * [View analytics](/guides/postmark/analytics) for your Postmark emails # Troubleshooting & FAQs Source: https://docs.sendpost.io/guides/postmark/troubleshooting Common issues, solutions, and frequently asked questions for Postmark integration with SendPost. ## Common Issues > [accordion] Emails Not Sending > > **Symptoms**: Emails are not being delivered through Postmark > > **Checklist**: > > * Verify your Postmark Server API Token is valid > * Ensure the TPSP is active and a **Message Stream** is selected > * Confirm you are sending with **`tpspTemplate`** (required for Postmark) > * Confirm **`ippool`** points to an IP Pool that routes to your Postmark provider > * Review SendPost event logs for errors > > **Test Your Token**: > > ```bash theme={null} > curl -X GET "https://api.postmarkapp.com/server" \ > -H "X-Postmark-Server-Token: YOUR_SERVER_API_TOKEN" > ``` > > If this returns 401, your token is invalid. > [accordion] Events Not Appearing > > **Symptoms**: Emails are sent but opens/clicks/deliveries/bounces not showing > > **Checklist**: > > * Verify the webhook is registered in Postmark (SendPost creates it at TPSP creation) > * Check webhook URL is `https://api.sendpost.io/tpsp/postmark/account/{account-id}` (or your `ApiUrl` equivalent) > * Ensure the webhook is for the **same Message Stream** you use for sending > * Confirm the URL is reachable from the internet (no firewall blocking Postmark) > * Wait a few minutes (events are batched for processing) > > **Verify in Postmark**: > > 1. Go to Postmark → Server → Webhooks > 2. Confirm a webhook exists for your Message Stream with the SendPost URL > 3. Verify triggers include Open, Click, Delivery, Bounce, Spam Complaint > [accordion] Bounces Not Processing > > **Symptoms**: Bounced emails not reflected in analytics > > **Check**: > > * Hard bounces (TypeCode 1 / HardBounce) → PMHardBounced (72) > * Other bounces → PMSoftBounced (73) > * Ensure Bounce trigger is enabled on the Postmark webhook > [accordion] API / Token Errors > > | Error Code | Meaning | Solution | > | - | - | - | > | 401 | Invalid or missing Server API Token | Check Key/Secret for the TPSP; regenerate in Postmark if needed | > | 422 | Invalid payload (e.g. From/To format, missing required fields) | Fix request (e.g. include `tpspTemplate`, valid From/To); no retry for same payload | > | 429 | Rate limit | SendPost retries automatically; consider increasing limits or throttling | > | 5xx | Postmark server error | SendPost retries; if persistent, check Postmark status | > [accordion] Missing tpspTemplate > > **Error**: Send fails when routing to Postmark > > **Cause**: Postmark sending in SendPost uses the Templates API; `tpspTemplate` is required. > > **Solution**: Always include `tpspTemplate` (Postmark template alias) in the request body when the email is routed to Postmark (e.g. via `ippool` pointing to Postmark). *** ## Getting Help If you're still experiencing issues: 1. **Check Logs**: Review detailed event logs in the SendPost dashboard 2. **Contact Support**: Reach out to SendPost support with: * Your account ID * TPSP ID * Message ID (if available) * Error messages and timestamps 3. **Verify NSQ**: Ensure the topic `tpsp_webhook_postmark` receives messages when Postmark sends webhooks; batcher and worker should process them and store events in ClickHouse *** ## FAQs > [accordion] Can I use multiple Postmark servers? > > Yes. Create a separate TPSP for each Postmark server (each with its own Server API Token and Message Stream). Each will have its own webhook and configuration. > [accordion] Does SendPost store my Postmark token securely? > > Yes. The Server API Token is stored as the provider Key/Secret and is not exposed in logs or API responses. > [accordion] Can I use Postmark for some emails and SendPost IPs for others? > > Yes. Use IP Pools to route a percentage of traffic through Postmark and the rest through SendPost infrastructure. > [accordion] What if the webhook endpoint is temporarily unavailable? > > Postmark may retry webhook delivery. Events will be processed once connectivity is restored. > [accordion] Why do I have to select a Message Stream? > > Postmark requires a Message Stream for both sending and webhook registration. The stream you select at setup is used for all sends and for the single webhook SendPost creates. > [accordion] Is a domain required for the Postmark provider? > > No. Postmark TPSP setup only needs the Server API Token and a selected Message Stream. You still whitelist your sending domain in SendPost for deliverability. > [accordion] What's the latency for event processing? > > Events are typically processed within a few seconds of being received from Postmark (webhook → NSQ → batcher → worker → ClickHouse). > [accordion] Are there limits on emails per day? > > SendPost does not impose hard limits; your Postmark plan limits apply. Configure throttling (e.g. Max Sends Per Hour) to match your Postmark capacity. # Tracking & Analytics Source: https://docs.sendpost.io/guides/sendgrid/analytics Track opens, clicks, bounces and configure rate limiting for SendGrid emails in SendPost. ## Open Tracking When `trackOpens` is enabled: * SendGrid inserts a tracking pixel into your HTML emails * Opens are tracked and reported as **SG Opened** events (ID: 20) * View open rates in the SendPost dashboard *** ## Click Tracking When `trackClicks` is enabled: * SendGrid rewrites links in your email to track clicks * Clicks are tracked and reported as **SG Clicked** events (ID: 21) * View click rates and URLs in the SendPost dashboard *** ## Viewing Analytics 1. Navigate to **Analytics** in your SendPost dashboard 2. Filter by: * **Provider**: Select your SendGrid provider * **Event Type**: Filter specific SendGrid events (14-25) * **Date Range**: Choose the time period * **Sub-account**: Filter by sub-account *** ## Rate Limiting & Throttling ### Default Rate Limits By default, SendGrid providers are configured with a rate limit of **100 emails per hour**. This limit is set at the provider level and applies to all emails sent through your SendGrid integration. ### Configuring Rate Limits You can easily adjust the rate limit through the SendPost UI: **1. Navigate to Providers** Go to **Settings** → **Providers** in your SendPost dashboard **2. Edit Provider** Click on your SendGrid provider to edit its settings **3. Adjust Rate Limit** Update the **Max Sends Per Hour** value to match your SendGrid plan limits or your desired sending rate **4. Save Changes** Save your changes. The new rate limit takes effect immediately. > [!NOTE] > > Rate limiting in SendPost is configured on an hourly basis. Adjust the hourly limit based on your SendGrid plan capacity and sending requirements. ### Provider-Level Throttling SendPost supports granular throttling for different email providers: | Provider | Description | | - | - | | Gmail | Throttle sending to Gmail addresses | | Yahoo | Throttle sending to Yahoo/AOL addresses | | Outlook | Throttle sending to Microsoft addresses | | Default | Throttle for all other domains | *** ## Next Steps * [Understand event types](/guides/sendgrid/event-types) for detailed event information * [Troubleshoot issues](/guides/sendgrid/troubleshooting) with analytics or rate limiting # SendGrid-Compatible API Source: https://docs.sendpost.io/guides/sendgrid/compatible-api Migrate from SendGrid with minimal code changes using SendPost's SendGrid-Compatible API. If you're currently using SendGrid and want to migrate to SendPost, we offer a **SendGrid-Compatible API** that minimizes code changes. *** ## IP Pool Requirement > [!WARNING] > > **Mandatory Requirement**: To use the SendGrid-Compatible API, you must have an IP Pool configured in both SendGrid and SendPost with **the same name**. The IP Pool name in your SendGrid requests (`ip_pool_name`) must match an IP Pool in SendPost that is configured to route traffic to your SendGrid provider. This ensures proper routing of emails through SendGrid. **Setup Steps**: 1. Note the IP Pool name you use in SendGrid (e.g., "transactional" or "marketing") 2. Create an IP Pool in SendPost with **the exact same name** 3. Configure the SendPost IP Pool to route traffic to your SendGrid provider *** ## Quick Migration Steps **1. Configure IP Pool** Create an IP Pool in SendPost with the same name as your SendGrid IP Pool, configured to route to SendGrid **2. Change the base URL** * From: `https://api.sendgrid.com` * To: `https://api.sendpost.io/v1/sendgrid` **3. Update the API key header** * From: `Authorization: Bearer SG.xxxx` * To: `X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY` **4. Send emails** Use the same payload format as before (including `ip_pool_name`) *** ## Migration Example > [tab] Before (SendGrid) > > ```bash theme={null} > curl -X POST "https://api.sendgrid.com/v3/mail/send" \ > -H "Authorization: Bearer SG.xxxxxxxxxxxx" \ > -H "Content-Type: application/json" \ > -d '{ > "personalizations": [{ > "to": [{"email": "john@example.com", "name": "John"}] > }], > "from": {"email": "sender@example.com"}, > "subject": "Hello World", > "content": [ > {"type": "text/plain", "value": "Hello!"}, > {"type": "text/html", "value": "

    Hello!

    "} > ], > "ip_pool_name": "transactional" > }' > ``` > [tab] After (SendPost) > > ```bash theme={null} > curl -X POST "https://api.sendpost.io/v1/sendgrid/v3/mail/send" \ > -H "X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "personalizations": [{ > "to": [{"email": "john@example.com", "name": "John"}] > }], > "from": {"email": "sender@example.com"}, > "subject": "Hello World", > "content": [ > {"type": "text/plain", "value": "Hello!"}, > {"type": "text/html", "value": "

    Hello!

    "} > ], > "ip_pool_name": "transactional" > }' > ``` > [!NOTE] > > The `ip_pool_name` in your request must match an IP Pool configured in SendPost that routes to SendGrid. Without this, the SendGrid-Compatible API will not know where to route your emails. *** ## Supported SendGrid Features | Feature | Supported | Notes | | - | - | - | | `from` / `to` / `subject` | ✅ | Direct mapping | | `content` (text/html) | ✅ | Supports both plain text and HTML | | `reply_to` | ✅ | Single reply-to address | | `headers` | ✅ | Custom headers preserved | | `custom_args` | ✅ | Merged into headers | | `categories` | ✅ | Mapped to SendPost groups | | `ip_pool_name` | ✅ | **Required** - Must match an IP Pool in SendPost configured for SendGrid routing | | `attachments` | ✅ | Base64 encoded attachments | | `personalizations` | ✅ | Multiple recipients with personalization | | `substitutions` | ✅ | Mapped to custom fields | | Open tracking | ✅ | `tracking_settings.open_tracking` | | Click tracking | ✅ | `tracking_settings.click_tracking` | *** ## Unsupported SendGrid Features > [!WARNING] > > The following SendGrid features are **not supported** and will return an error if present: | Feature | Alternative | | - | - | | `template_id` | Use SendPost's native template API or include content directly | | `reply_to_list` | Use single `reply_to` address | | `send_at` (scheduled sending) | Not available through this endpoint | | `batch_id` | Not supported | | `asm` (suppression groups) | Use SendPost's `{{unsubscribe}}` template variable | | `mail_settings` | Not supported | | `subscription_tracking` | Use SendPost's `{{unsubscribe}}` template variable | | `ganalytics` | Not supported | | `attachments.disposition` | All attachments treated as standard | | `attachments.content_id` | Inline images via CID not supported | **Error Response for Unsupported Fields**: ```json theme={null} { "errors": [{ "message": "Field 'template_id' is not supported. Please use SendPost's native template API or include content directly.", "field": "template_id" }] } ``` *** ## Response Mapping | SendGrid Response | SendPost Behavior | | - | - | | HTTP 202 Accepted | SendPost returns 202 with empty body on success | | HTTP 400 Bad Request | Validation errors in SendGrid format | | HTTP 401 Unauthorized | Invalid or missing API key | | HTTP 413 Payload Too Large | Request exceeds 30MB limit | *** ## Next Steps * [Understand event types](/guides/sendgrid/event-types) for tracking email status * [View analytics](/guides/sendgrid/analytics) for your SendGrid emails * [Troubleshoot issues](/guides/sendgrid/troubleshooting) with the compatible API # SendGrid Event Types Source: https://docs.sendpost.io/guides/sendgrid/event-types Understand SendGrid event types and how they map to SendPost for tracking email delivery and engagement. SendGrid events are tracked with specific event type IDs in SendPost, allowing you to distinguish between native SendPost events and SendGrid events. *** ## SendGrid Event Types | Event Type | ID | Description | | - | - | - | | SG Sent | 14 | Email accepted by SendGrid for delivery | | SG Delivered | 15 | Email successfully delivered to recipient | | SG Deferred | 16 | Temporary delivery delay (SendGrid will retry) | | SG Dropped | 17 | Email dropped by SendGrid (invalid address, etc.) | | SG Hard Bounced | 18 | Permanent delivery failure | | SG Soft Bounced | 19 | Temporary delivery failure (blocked) | | SG Opened | 20 | Recipient opened the email | | SG Clicked | 21 | Recipient clicked a link | | SG Spam Report | 22 | Recipient marked email as spam | | SG Unsubscribe | 23 | Recipient unsubscribed | | SG Group Unsubscribe | 24 | Recipient unsubscribed from group | | SG Group Resubscribe | 25 | Recipient resubscribed to group | *** ## Bounce Type Details SendGrid categorizes bounces into two types: > [accordion] Hard Bounce (ID: 18) > > Permanent failure (invalid email, domain doesn't exist). These addresses should be removed from your list. > [accordion] Soft Bounce (ID: 19) > > Temporary failure (mailbox full, temporarily blocked). SendGrid may retry these automatically. Consider these as temporary issues. *** ## Event Data Each SendGrid event includes: * Message ID (for correlation) * Recipient email * Timestamp * SMTP response code (for bounces) * User agent (for opens) * Clicked URL (for clicks) * SendGrid-specific IDs (`sg_event_id`, `sg_message_id`) *** ## Event Type Quick Reference | Event | ID | Webhook Event Name | | - | - | - | | Sent | 14 | `processed` | | Delivered | 15 | `delivered` | | Deferred | 16 | `deferred` | | Dropped | 17 | `dropped` | | Hard Bounce | 18 | `bounce` (type ≠ blocked) | | Soft Bounce | 19 | `bounce` (type = blocked) | | Open | 20 | `open` | | Click | 21 | `click` | | Spam | 22 | `spamreport` | | Unsubscribe | 23 | `unsubscribe` | *** ## Next Steps * [View analytics](/guides/sendgrid/analytics) to see event statistics * [Troubleshoot issues](/guides/sendgrid/troubleshooting) with event processing # SendGrid Integration Source: https://docs.sendpost.io/guides/sendgrid/overview Connect your SendGrid account to SendPost for unified email management, advanced analytics, and enhanced deliverability monitoring. SendPost's SendGrid integration allows you to use your existing SendGrid account as a **Third-Party Sending Provider (TPSP)**. This means you can: * Send emails through SendGrid while using SendPost's unified API * Receive and process SendGrid events (opens, clicks, bounces, etc.) in SendPost * View all email analytics in one centralized dashboard * Apply SendPost's intelligent routing and throttling to your SendGrid traffic Additionally, SendPost offers a **SendGrid-Compatible API** that allows you to migrate from SendGrid with minimal code changes. *** ## Why Use SendGrid with SendPost? | Feature | SendGrid Alone | SendGrid + SendPost | | - | - | - | | Multiple ESP management | ❌ | ✅ Unified dashboard for all providers | | Cross-provider analytics | ❌ | ✅ Compare performance across ESPs | | Advanced throttling | Basic | ✅ Per-provider rate limiting (Gmail, Yahoo, etc.) | | Failover routing | ❌ | ✅ Automatic fallback to other providers | | Centralized event logs | ❌ | ✅ All events in one place | | Sub-account management | Limited | ✅ Flexible sub-account hierarchy | *** ## What's Covered in This Guide > [card] [Setting Up](/guides/sendgrid/setup) > > Configure SendGrid as a provider in SendPost with automatic webhook setup > [card] [Sending Emails](/guides/sendgrid/sending-emails) > > Send emails through SendGrid using the SendPost API with IP Pool routing > [card] [Compatible API](/guides/sendgrid/compatible-api) > > Migrate from SendGrid with minimal code changes using our compatible API > [card] [Event Types](/guides/sendgrid/event-types) > > Understand SendGrid event types and how they map to SendPost > [card] [Analytics](/guides/sendgrid/analytics) > > Track opens, clicks, bounces and configure rate limiting > [card] [Troubleshooting](/guides/sendgrid/troubleshooting) > > Common issues, FAQs, and getting help *** ## Quick Reference ### Key Endpoints | Purpose | URL | | - | - | | Send Email (Native) | `POST /api/v1/subaccount/email/` | | Send Email (SendGrid Compatible) | `POST /v1/sendgrid/v3/mail/send` | | View Events | SendPost Dashboard → Events | ### Setup Checklist **1. Create SendGrid API Key** Create API key with Mail Send + Event Webhook permissions **2. Add Provider** Add SendGrid provider in SendPost dashboard **3. Configure IP Pool** Create an IP Pool in SendPost configured to route traffic to SendGrid **4. Whitelist Domain** Whitelist your sending domain in SendPost (same domain used in SendGrid) **5. Test** Send a test email with the `ippool` parameter **6. Confirm Events** Confirm events appear in SendPost analytics # Sending Emails via SendGrid Source: https://docs.sendpost.io/guides/sendgrid/sending-emails Send emails through SendGrid using the SendPost API with IP Pool routing. Once your SendGrid provider and IP Pool are configured, you can send emails through SendGrid using the standard SendPost API. > [!NOTE] > > **Important**: You must include the `ippool` parameter in your API request to route emails through SendGrid. *** ## Basic Email Example ```bash theme={null} curl -X POST "https://api.sendpost.io/api/v1/subaccount/email/" \ -H "X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": { "email": "sender@yourdomain.com", "name": "Your Name" }, "to": [{ "email": "recipient@example.com", "name": "Recipient Name" }], "subject": "Hello from SendPost via SendGrid", "htmlBody": "

    Hello!

    This email is sent through SendGrid.

    ", "textBody": "Hello! This email is sent through SendGrid.", "ippool": "sendgrid-pool", "trackOpens": true, "trackClicks": true }' ``` *** ## Email with Personalization ```bash theme={null} curl -X POST "https://api.sendpost.io/api/v1/subaccount/email/" \ -H "X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": { "email": "sender@yourdomain.com", "name": "Your Company" }, "to": [{ "email": "john@example.com", "name": "John Doe", "customFields": { "firstName": "John", "accountType": "Premium" } }], "subject": "Welcome {{firstName}}!", "htmlBody": "

    Welcome {{firstName}}!

    Your {{accountType}} account is ready.

    ", "ippool": "sendgrid-pool", "trackOpens": true, "trackClicks": true }' ``` *** ## Using SendGrid IP Pools If you have multiple IP Pools configured in your SendGrid account and want to specify which SendGrid IP Pool to use for sending, you can pass the `tpspIppool` parameter in your API request. > [!NOTE] > > The `tpspIppool` field is optional. Use it when you want to route emails through a specific IP Pool on the SendGrid side, separate from the SendPost IP Pool routing. **Parameters**: * `ippool`: The SendPost IP Pool that routes traffic to SendGrid (required) * `tpspIppool`: The IP Pool name configured in your SendGrid account (optional) ```bash theme={null} curl -X POST "https://api.sendpost.io/api/v1/subaccount/email/" \ -H "X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": { "email": "sender@yourdomain.com", "name": "Your Company" }, "to": [{ "email": "recipient@example.com", "name": "Recipient Name" }], "subject": "Hello from SendPost via SendGrid", "htmlBody": "

    Hello!

    This email is sent through a specific SendGrid IP Pool.

    ", "ippool": "sendgrid-pool", "tpspIppool": "transactional", "trackOpens": true, "trackClicks": true }' ``` In this example: * `ippool: "sendgrid-pool"` - Routes the email through SendPost's IP Pool configured for SendGrid * `tpspIppool: "transactional"` - Sends the email via the "transactional" IP Pool in your SendGrid account *** ## Response **Success Response** (HTTP 200): ```json theme={null} [ { "messageId": "abc123-def456-ghi789", "errorCode": 0, "to": "recipient@example.com" } ] ``` *** ## Next Steps * [Migrate from SendGrid](/guides/sendgrid/compatible-api) using the SendGrid-Compatible API * [Understand event types](/guides/sendgrid/event-types) for tracking email status * [View analytics](/guides/sendgrid/analytics) for your SendGrid emails # Setting Up SendGrid Integration Source: https://docs.sendpost.io/guides/sendgrid/setup Configure SendGrid as a Third-Party Sending Provider in SendPost with automatic webhook setup. ## Prerequisites Before setting up the SendGrid integration, ensure you have: ### 1. SendGrid Account * An active SendGrid account * API key with **Mail Send** permissions ### 2. SendGrid API Key To create an API key in SendGrid: **1. Log in to SendGrid** Log in to your [SendGrid Dashboard](https://app.sendgrid.com) **2. Navigate to API Keys** Go to **Settings** → **API Keys** **3. Create API Key** Click **Create API Key** and choose **Restricted Access** **4. Set Permissions** Enable the following permissions: * **Mail Send**: Full Access * **Event Webhook Settings**: Full Access (for automatic webhook setup) **5. Save Your Key** Click **Create & View** and **copy your API key** (you won't be able to see it again) ### 3. SendPost Account * A SendPost account with admin access * At least one sub-account created *** ## Setting Up SendGrid Integration ### Step 1: Navigate to Providers 1. Log in to your [SendPost Dashboard](https://app.sendpost.io) 2. Go to **Settings** → **Providers** (or navigate to the Providers page) 3. Click the **NEW** button ### Step 2: Configure SendGrid Provider 1. **Name**: Enter a descriptive name (e.g., "Production SendGrid", "Marketing SendGrid") 2. **Type**: Select **SendGrid** from the dropdown 3. **Key**: Paste your SendGrid API key 4. Click **Save** ### Step 3: Automatic Webhook Configuration When you save the provider, SendPost automatically: > [!TIP] > > Registers a webhook with SendGrid > [!TIP] > > Configures the webhook to receive all supported events > [!TIP] > > Creates the necessary processing infrastructure **Webhook URL Format**: `https://api.sendpost.io/tpsp/sendgrid/account/{your-account-id}` **Events Configured**: * Processed (sent) * Delivered * Bounced * Dropped * Opened * Clicked * Spam Reports * Unsubscribes ### Step 4: Configure IP Pool for SendGrid Routing Before sending emails via SendGrid, you need to configure an IP Pool in SendPost that routes traffic to your SendGrid provider. #### Why IP Pools? IP Pools in SendPost allow you to control how your email traffic is distributed between SendPost's native infrastructure and third-party providers like SendGrid. This enables: * **Volume-based routing**: Split your email volume between SendGrid and SendPost infrastructure * **Easy traffic management**: Adjust the percentage of emails sent via SendGrid vs SendPost at any time * **Gradual migration**: Start with a small percentage on SendGrid and increase as needed * **Failover capability**: Route traffic to SendGrid when SendPost IPs are warming up #### Setting Up IP Pool for SendGrid **1. Create IP Pool** 1. Go to **Settings** → **IP Pools** in your SendPost dashboard 2. Click **Create New IP Pool** 3. Enter a descriptive name (e.g., "sendgrid-pool" or "marketing-sendgrid") **2. Configure Routing** 1. In the IP Pool settings, configure the routing to use your SendGrid provider 2. Set the volume percentage you want to route through SendGrid 3. You can easily adjust this percentage later to control traffic distribution **3. Save Configuration** Save your IP Pool configuration. The pool name will be used in your API calls. #### Volume-Based Routing You can configure what percentage of your email volume goes through SendGrid vs SendPost's native infrastructure: | Configuration | SendGrid | SendPost Infrastructure | | - | - | - | | 100% SendGrid | All emails via SendGrid | None | | 50/50 Split | 50% of emails | 50% of emails | | SendGrid Backup | 0% (failover only) | 100% primary | > [!NOTE] > > You can change the volume distribution at any time through the SendPost UI without any code changes. ### Step 5: Whitelist Your Sending Domain You must whitelist the same sending domain in SendPost that you use in SendGrid. > [!WARNING] > > **Important**: The domain you use for sending emails (e.g., `yourdomain.com`) must be whitelisted in SendPost. This ensures proper email routing and deliverability. 1. Go to **Settings** → **Domains** in your SendPost dashboard 2. Click **Add Domain** 3. Enter the same domain you have configured in SendGrid (e.g., `yourdomain.com`) 4. Complete the domain verification process > [!NOTE] > > If you're using multiple sending domains in SendGrid, you need to whitelist each domain in SendPost. *** ## Next Steps Once your SendGrid integration is set up, you can: * [Send emails via SendGrid](/guides/sendgrid/sending-emails) using the SendPost API * [Migrate from SendGrid](/guides/sendgrid/compatible-api) using the compatible API * [View analytics](/guides/sendgrid/analytics) for your SendGrid emails # Troubleshooting & FAQs Source: https://docs.sendpost.io/guides/sendgrid/troubleshooting Common issues, solutions, and frequently asked questions for SendGrid integration with SendPost. ## Common Issues > [accordion] Emails Not Sending > > **Symptoms**: Emails are not being delivered through SendGrid > > **Checklist**: > > * Verify your SendGrid API key is valid and has Mail Send permissions > * Check that the TPSP is active in SendPost > * Review the SendPost event logs for errors > * Confirm your SendGrid account is in good standing > > **Test Your API Key**: > > ```bash theme={null} > curl -X GET "https://api.sendgrid.com/v3/user/profile" \ > -H "Authorization: Bearer YOUR_SENDGRID_API_KEY" > ``` > > If this returns 401, your API key is invalid. > [accordion] Events Not Appearing > > **Symptoms**: Emails are sent but opens/clicks/bounces not showing > > **Checklist**: > > * Verify webhook is registered in SendGrid Dashboard > * Check webhook URL is correct > * Ensure webhook events are enabled > * Wait a few minutes (events are batched for processing) > > **Verify Webhook in SendGrid**: > > 1. Go to SendGrid → Settings → Mail Settings → Event Webhook > 2. Confirm URL shows: `https://api.sendpost.io/tpsp/sendgrid/account/{account-id}` > 3. Verify all event checkboxes are enabled > [accordion] Bounces Not Processing > > **Symptoms**: Bounced emails not reflected in analytics > > **Check**: > > * Review SMTP codes in event details > * Hard bounces (5xx codes) = permanent failures > * Soft bounces (4xx codes) = temporary failures > * Ensure bounce events are enabled in webhook settings > [accordion] API Key Errors > > | Error Code | Meaning | Solution | > | - | - | - | > | 401 | Invalid API key | Regenerate API key in SendGrid | > | 403 | Insufficient permissions | Update API key permissions | > | 429 | Rate limit exceeded | Wait and retry, or increase limits | > [accordion] SendGrid-Compatible API Errors > > **400 Bad Request with field error**: > > ```json theme={null} > { > "errors": [{ > "message": "Field 'template_id' is not supported...", > "field": "template_id" > }] > } > ``` > > **Solution**: Remove the unsupported field from your request > > **413 Payload Too Large**: > **Solution**: Reduce request size below 30MB *** ## Getting Help If you're still experiencing issues: 1. **Check Logs**: Review detailed event logs in SendPost dashboard 2. **Contact Support**: Reach out to SendPost support with: * Your account ID * TPSP ID * Message ID (if available) * Error messages * Timestamp of the issue *** ## FAQs > [accordion] Can I use multiple SendGrid accounts? > > Yes! Create a separate TPSP for each SendGrid account. Each will have its own webhook and configuration. > [accordion] Does SendPost store my SendGrid API key securely? > > Yes, all API keys are encrypted at rest and never exposed in logs or API responses. > [accordion] Can I use SendGrid for some emails and SendPost IPs for others? > > Yes, SendPost supports intelligent routing. You can configure rules to route specific traffic through SendGrid. > [accordion] What happens if the webhook endpoint is temporarily unavailable? > > SendGrid will retry webhook delivery. Events will be processed once connectivity is restored. > [accordion] Are duplicate events possible? > > SendGrid may occasionally send duplicate events. SendPost handles deduplication using the `sg_event_id`. > [accordion] Will my existing SendGrid templates work? > > SendGrid templates (`template_id`) are not supported through the compatible API. You'll need to include the content directly or use SendPost's native template system. > [accordion] Can I gradually migrate traffic? > > Yes! You can run both systems in parallel during migration. Route a percentage of traffic to SendPost while keeping some on SendGrid directly. > [accordion] What's the latency for event processing? > > Events are typically processed within 1-5 seconds of being received from SendGrid. > [accordion] Is there a limit on emails per day? > > SendPost doesn't impose hard limits, but your SendGrid plan limits still apply. Configure throttling to match your SendGrid limits. # Tracking & Analytics Source: https://docs.sendpost.io/guides/sparkpost/analytics Track opens, clicks, bounces and configure rate limiting for SparkPost emails in SendPost. ## Open Tracking When `trackOpens` is enabled: * SparkPost inserts a tracking pixel into your HTML emails * Opens are tracked and reported as **SP Opened** events (ID: 43) * Initial opens (`initial_open`) and subsequent opens (`open`) are both captured * View open rates in the SendPost dashboard *** ## Click Tracking When `trackClicks` is enabled: * SparkPost rewrites links in your email to track clicks * Clicks are tracked and reported as **SP Clicked** events (ID: 44) * Clicked URL is captured in event metadata * View click rates and URLs in the SendPost dashboard *** ## Viewing Analytics 1. Navigate to **Analytics** in your SendPost dashboard 2. Filter by: * **Provider**: Select your SparkPost provider * **Event Type**: Filter specific SparkPost events (37-46) * **Date Range**: Choose the time period * **Sub-account**: Filter by sub-account *** ## Rate Limiting & Throttling ### Default Rate Limits By default, SparkPost providers are configured with a rate limit of **100 emails per hour**. This limit is set at the provider level and applies to all emails sent through your SparkPost integration. ### Configuring Rate Limits You can easily adjust the rate limit through the SendPost UI: **1. Navigate to Providers** Go to **Settings** → **Providers** in your SendPost dashboard **2. Edit Provider** Click on your SparkPost provider to edit its settings **3. Adjust Rate Limit** Update the **Max Sends Per Hour** value to match your SparkPost plan limits or your desired sending rate **4. Save Changes** Save your changes. The new rate limit takes effect immediately. > [!NOTE] > > Rate limiting in SendPost is configured on an hourly basis. Adjust the hourly limit based on your SparkPost plan capacity and sending requirements. ### Provider-Level Throttling SendPost supports granular throttling for different email providers: | Provider | Description | | - | - | | Gmail | Throttle sending to Gmail addresses | | Yahoo | Throttle sending to Yahoo/AOL addresses | | Microsoft | Throttle sending to Microsoft addresses (Outlook, Hotmail) | | Default | Throttle for all other domains | *** ## Next Steps * [Understand event types](/guides/sparkpost/event-types) for detailed event information * [Troubleshoot issues](/guides/sparkpost/troubleshooting) with analytics or rate limiting # SparkPost Event Types Source: https://docs.sendpost.io/guides/sparkpost/event-types Understand SparkPost event types, bounce classifications, and how they map to SendPost. SparkPost events are tracked with specific event type IDs in SendPost, allowing you to distinguish between native SendPost events and SparkPost events. *** ## SparkPost Event Types | Event Type | ID | SparkPost Event | Description | | - | - | - | - | | SP Sent | 37 | `injection` | Email accepted by SparkPost for delivery | | SP Delivered | 38 | `delivery` | Email successfully delivered to recipient | | SP Deferred | 39 | `delay` | Temporary delivery delay (SparkPost will retry) | | SP Dropped | 40 | `policy_rejection` | Email dropped by SparkPost policy | | SP Hard Bounced | 41 | `bounce`, `out_of_band` | Permanent delivery failure | | SP Soft Bounced | 42 | (reserved) | Temporary delivery failure | | SP Opened | 43 | `open`, `initial_open` | Recipient opened the email | | SP Clicked | 44 | `click` | Recipient clicked a link | | SP Spam Report | 45 | `spam_complaint` | Recipient marked email as spam | | SP Unsubscribe | 46 | `list_unsubscribe`, `link_unsubscribe` | Recipient unsubscribed | *** ## Bounce Type Details SparkPost categorizes bounces into different types: > [accordion] Hard Bounce (ID: 41) > > Permanent failure (invalid email, domain doesn't exist). Includes both synchronous `bounce` events and asynchronous `out_of_band` bounces. These addresses should be removed from your list. > [accordion] Soft Bounce (ID: 42) > > Temporary failure. SparkPost may retry these automatically. Consider these as temporary issues. *** ## SparkPost Bounce Classes SparkPost provides detailed bounce classification via `bounce_class`: | Bounce Class | Category | Description | | - | - | - | | 1 | Undetermined | Unable to classify | | 10 | Invalid Recipient | Hard bounce - invalid address | | 20 | Soft Bounce | Temporary failure | | 21 | DNS Failure | Temporary DNS lookup failure | | 22 | Mailbox Full | Recipient's mailbox is full | | 23 | Too Large | Message size too large | | 24 | Timeout | Connection timeout | | 25 | Admin Failure | Administrative failure | | 30 | Generic Bounce | No RCPT permission | | 40 | Generic Bounce | Network error | | 50 | Mail Block | Blocked by recipient | | 51 | Spam Related | Blocked as spam | | 52 | Spam Content | Content flagged as spam | | 53 | Prohibited Attachment | Attachment type blocked | | 60 | Auto-Reply | Auto-reply message | | 70 | Transient Failure | Temporary system failure | | 80 | Subscribe | Subscribe request | | 90 | Unsubscribe | Unsubscribe request | | 100 | Challenge-Response | Challenge-response system | *** ## Event Data Each SparkPost event includes: * Message ID (for correlation) * Recipient email * Timestamp * SMTP response code (for bounces) * User agent (for opens) * Clicked URL (for clicks) * SparkPost-specific IDs (`message_id`, `transmission_id`) * Bounce class (for bounce events) * Geographic information (country, region, city) *** ## Event Type Quick Reference | Event | ID | SparkPost Event Name | | - | - | - | | Sent | 37 | `injection` | | Delivered | 38 | `delivery` | | Deferred | 39 | `delay` | | Dropped | 40 | `policy_rejection` | | Hard Bounce | 41 | `bounce`, `out_of_band` | | Soft Bounce | 42 | (reserved) | | Open | 43 | `open`, `initial_open` | | Click | 44 | `click` | | Spam | 45 | `spam_complaint` | | Unsubscribe | 46 | `list_unsubscribe`, `link_unsubscribe` | *** ## Next Steps * [View analytics](/guides/sparkpost/analytics) to see event statistics * [Troubleshoot issues](/guides/sparkpost/troubleshooting) with event processing # SparkPost Integration Source: https://docs.sendpost.io/guides/sparkpost/overview Connect your SparkPost account to SendPost for unified email management, advanced analytics, and enhanced deliverability monitoring. SendPost's SparkPost integration allows you to use your existing SparkPost account as a **Third-Party Sending Provider (TPSP)**. This means you can: * Send emails through SparkPost while using SendPost's unified API * Receive and process SparkPost events (opens, clicks, bounces, etc.) in SendPost * View all email analytics in one centralized dashboard * Apply SendPost's intelligent routing and throttling to your SparkPost traffic *** ## Why Use SparkPost with SendPost? | Feature | SparkPost Alone | SparkPost + SendPost | | - | - | - | | Multiple ESP management | ❌ | ✅ Unified dashboard for all providers | | Cross-provider analytics | ❌ | ✅ Compare performance across ESPs | | Advanced throttling | Basic | ✅ Per-provider rate limiting (Gmail, Yahoo, etc.) | | Failover routing | ❌ | ✅ Automatic fallback to other providers | | Centralized event logs | ❌ | ✅ All events in one place | | Sub-account management | Limited | ✅ Flexible sub-account hierarchy | *** ## What's Covered in This Guide > [card] [Setting Up](/guides/sparkpost/setup) > > Configure SparkPost as a provider in SendPost with automatic webhook setup > [card] [Sending Emails](/guides/sparkpost/sending-emails) > > Send emails through SparkPost using the SendPost API with IP Pool routing > [card] [Event Types](/guides/sparkpost/event-types) > > Understand SparkPost event types and bounce classifications > [card] [Analytics](/guides/sparkpost/analytics) > > Track opens, clicks, bounces and configure rate limiting > [card] [Troubleshooting](/guides/sparkpost/troubleshooting) > > Common issues, FAQs, and getting help *** ## Quick Reference ### Key Endpoints | Purpose | URL | | - | - | | Send Email | `POST /api/v1/subaccount/email/` | | View Events | SendPost Dashboard → Events | ### Setup Checklist **1. Create SparkPost API Key** Create API key with Transmissions + Webhooks permissions **2. Add Provider** Add SparkPost provider in SendPost dashboard **3. Configure IP Pool** Create an IP Pool in SendPost configured to route traffic to SparkPost **4. Whitelist Domain** Whitelist your sending domain in SendPost (same domain used in SparkPost) **5. Test** Send a test email with the `ippool` parameter **6. Confirm Events** Confirm events appear in SendPost analytics # Sending Emails via SparkPost Source: https://docs.sendpost.io/guides/sparkpost/sending-emails Send emails through SparkPost using the SendPost API with IP Pool routing. Once your SparkPost provider and IP Pool are configured, you can send emails through SparkPost using the standard SendPost API. > [!NOTE] > > **Important**: You must include the `ippool` parameter in your API request to route emails through SparkPost. *** ## Basic Email Example ```bash theme={null} curl -X POST "https://api.sendpost.io/api/v1/subaccount/email/" \ -H "X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": { "email": "sender@yourdomain.com", "name": "Your Name" }, "to": [{ "email": "recipient@example.com", "name": "Recipient Name" }], "subject": "Hello from SendPost via SparkPost", "htmlBody": "

    Hello!

    This email is sent through SparkPost.

    ", "textBody": "Hello! This email is sent through SparkPost.", "ippool": "sparkpost-pool", "trackOpens": true, "trackClicks": true }' ``` *** ## Email with Personalization ```bash theme={null} curl -X POST "https://api.sendpost.io/api/v1/subaccount/email/" \ -H "X-SubAccount-ApiKey: YOUR_SENDPOST_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "from": { "email": "sender@yourdomain.com", "name": "Your Company" }, "to": [{ "email": "john@example.com", "name": "John Doe", "customFields": { "firstName": "John", "accountType": "Premium" } }], "subject": "Welcome {{firstName}}!", "htmlBody": "

    Welcome {{firstName}}!

    Your {{accountType}} account is ready.

    ", "ippool": "sparkpost-pool", "trackOpens": true, "trackClicks": true }' ``` *** ## Response **Success Response** (HTTP 200): ```json theme={null} [ { "messageId": "abc123-def456-ghi789", "errorCode": 0, "to": "recipient@example.com" } ] ``` *** ## Next Steps * [Understand event types](/guides/sparkpost/event-types) for tracking email status * [View analytics](/guides/sparkpost/analytics) for your SparkPost emails * [Troubleshoot issues](/guides/sparkpost/troubleshooting) if you encounter problems # Setting Up SparkPost Integration Source: https://docs.sendpost.io/guides/sparkpost/setup Configure SparkPost as a Third-Party Sending Provider in SendPost with automatic webhook setup. ## Prerequisites Before setting up the SparkPost integration, ensure you have: ### 1. SparkPost Account * An active SparkPost account * API key with appropriate permissions ### 2. SparkPost API Key To create an API key in SparkPost: **1. Log in to SparkPost** Log in to your [SparkPost Dashboard](https://app.sparkpost.com) **2. Navigate to API Keys** Go to **Configuration** → **API Keys** **3. Create API Key** Click **Create API Key** **4. Set Permissions** Configure the following permissions: * **Transmissions**: Read/Write (required for sending) * **Webhooks**: Read/Write (required for event tracking) **5. Save Your Key** Click **Create API Key** and **copy your API key** (you won't be able to see it again) ### 3. SendPost Account * A SendPost account with admin access * At least one sub-account created *** ## Setting Up SparkPost Integration ### Step 1: Navigate to Providers 1. Log in to your [SendPost Dashboard](https://app.sendpost.io) 2. Go to **Settings** → **Providers** (or navigate to the Providers page) 3. Click the **NEW** button ### Step 2: Configure SparkPost Provider 1. **Name**: Enter a descriptive name (e.g., "Production SparkPost", "Marketing SparkPost") 2. **Type**: Select **SparkPost** from the dropdown 3. **Key**: Paste your SparkPost API key 4. Click **Save** ### Step 3: Automatic Webhook Configuration When you save the provider, SendPost automatically: > [!TIP] > > Registers a webhook with SparkPost > [!TIP] > > Configures the webhook to receive all supported events > [!TIP] > > Creates the necessary processing infrastructure **Webhook URL Format**: `https://api.sendpost.io/tpsp/sparkpost/account/{your-account-id}` **Events Configured**: * Injection (sent) * Delivery * Bounce * Out of Band (async bounces) * Delay * Policy Rejection * Spam Complaint * Open / Initial Open * Click * List Unsubscribe / Link Unsubscribe ### Step 4: Configure IP Pool for SparkPost Routing Before sending emails via SparkPost, you need to configure an IP Pool in SendPost that routes traffic to your SparkPost provider. #### Why IP Pools? IP Pools in SendPost allow you to control how your email traffic is distributed between SendPost's native infrastructure and third-party providers like SparkPost. This enables: * **Volume-based routing**: Split your email volume between SparkPost and SendPost infrastructure * **Easy traffic management**: Adjust the percentage of emails sent via SparkPost vs SendPost at any time * **Gradual migration**: Start with a small percentage on SparkPost and increase as needed * **Failover capability**: Route traffic to SparkPost when SendPost IPs are warming up #### Setting Up IP Pool for SparkPost **1. Create IP Pool** 1. Go to **Settings** → **IP Pools** in your SendPost dashboard 2. Click **Create New IP Pool** 3. Enter a descriptive name (e.g., "sparkpost-pool" or "transactional-sparkpost") **2. Configure Routing** 1. In the IP Pool settings, configure the routing to use your SparkPost provider 2. Set the volume percentage you want to route through SparkPost 3. You can easily adjust this percentage later to control traffic distribution **3. Save Configuration** Save your IP Pool configuration. The pool name will be used in your API calls. #### Volume-Based Routing You can configure what percentage of your email volume goes through SparkPost vs SendPost's native infrastructure: | Configuration | SparkPost | SendPost Infrastructure | | - | - | - | | 100% SparkPost | All emails via SparkPost | None | | 50/50 Split | 50% of emails | 50% of emails | | SparkPost Backup | 0% (failover only) | 100% primary | > [!NOTE] > > You can change the volume distribution at any time through the SendPost UI without any code changes. ### Step 5: Whitelist Your Sending Domain You must whitelist the same sending domain in SendPost that you use in SparkPost. > [!WARNING] > > **Important**: The domain you use for sending emails (e.g., `yourdomain.com`) must be whitelisted in SendPost. This ensures proper email routing and deliverability. 1. Go to **Settings** → **Domains** in your SendPost dashboard 2. Click **Add Domain** 3. Enter the same domain you have configured in SparkPost (e.g., `yourdomain.com`) 4. Complete the domain verification process > [!NOTE] > > If you're using multiple sending domains in SparkPost, you need to whitelist each domain in SendPost. *** ## Next Steps Once your SparkPost integration is set up, you can: * [Send emails via SparkPost](/guides/sparkpost/sending-emails) using the SendPost API * [Understand event types](/guides/sparkpost/event-types) for tracking email status * [View analytics](/guides/sparkpost/analytics) for your SparkPost emails # Troubleshooting & FAQs Source: https://docs.sendpost.io/guides/sparkpost/troubleshooting Common issues, solutions, and frequently asked questions for SparkPost integration with SendPost. ## Common Issues > [accordion] Emails Not Sending > > **Symptoms**: Emails are not being delivered through SparkPost > > **Checklist**: > > * Verify your SparkPost API key is valid and has Transmissions permissions > * Check that the TPSP is active in SendPost > * Review the SendPost event logs for errors > * Confirm your SparkPost account is in good standing > * Verify your sending domain is properly configured in SparkPost > > **Test Your API Key**: > > ```bash theme={null} > curl -X GET "https://api.sparkpost.com/api/v1/account" \ > -H "Authorization: YOUR_SPARKPOST_API_KEY" > ``` > > If this returns 401, your API key is invalid. > [accordion] Events Not Appearing > > **Symptoms**: Emails are sent but opens/clicks/bounces not showing > > **Checklist**: > > * Verify webhook is registered in SparkPost Dashboard > * Check webhook URL is correct > * Ensure webhook events are enabled > * Wait a few minutes (events are batched for processing) > > **Verify Webhook in SparkPost**: > > 1. Go to SparkPost → Configuration → Webhooks > 2. Confirm URL shows: `https://api.sendpost.io/tpsp/sparkpost/account/{account-id}` > 3. Verify all event checkboxes are enabled > [accordion] Bounces Not Processing > > **Symptoms**: Bounced emails not reflected in analytics > > **Check**: > > * Review bounce class in event details > * Hard bounces (class 10, 30, 50-52) = permanent failures > * Soft bounces (class 20-25, 70) = temporary failures > * Ensure bounce events are enabled in webhook settings > [accordion] API Key Errors > > | Error Code | Meaning | Solution | > | - | - | - | > | 401 | Invalid API key | Regenerate API key in SparkPost | > | 403 | Insufficient permissions | Update API key permissions (needs Transmissions + Webhooks) | > | 429 | Rate limit exceeded | Wait and retry, or increase limits | > | 400 | Bad Request | Check payload format and required fields | *** ## Getting Help If you're still experiencing issues: 1. **Check Logs**: Review detailed event logs in SendPost dashboard 2. **Contact Support**: Reach out to SendPost support with: * Your account ID * TPSP ID * Message ID (if available) * Error messages * Timestamp of the issue *** ## FAQs > [accordion] Can I use multiple SparkPost accounts? > > Yes! Create a separate TPSP for each SparkPost account. Each will have its own webhook and configuration. > [accordion] Does SendPost store my SparkPost API key securely? > > Yes, all API keys are encrypted at rest and never exposed in logs or API responses. > [accordion] Can I use SparkPost for some emails and SendPost IPs for others? > > Yes, SendPost supports intelligent routing. You can configure rules to route specific traffic through SparkPost. > [accordion] What SparkPost regions are supported? > > SendPost uses the SparkPost US endpoint (`api.sparkpost.com`). If you use SparkPost EU, contact support for configuration assistance. > [accordion] What happens if the webhook endpoint is temporarily unavailable? > > SparkPost will retry webhook delivery. Events will be processed once connectivity is restored. > [accordion] Are duplicate events possible? > > SparkPost may occasionally send duplicate events. SendPost handles deduplication using the SparkPost message ID. > [accordion] What's the difference between open and initial\_open events? > > `initial_open` is the first time a recipient opens an email. `open` events may include subsequent opens. Both are mapped to the SP Opened event type (ID: 43). > [accordion] What's the latency for event processing? > > Events are typically processed within 1-5 seconds of being received from SparkPost. > [accordion] Is there a limit on emails per day? > > SendPost doesn't impose hard limits, but your SparkPost plan limits still apply. Configure throttling to match your SparkPost limits. > [accordion] How does SparkPost handle delay events? > > Delay events indicate temporary delivery issues. SparkPost will automatically retry. These events are tracked but not counted as failures. # Introduction Source: https://docs.sendpost.io/index Welcome to SendPost API Documentation. SendPost provides email API and SMTP relay which can be used not just to send & measure but also alert & optimised email sending. You can use SendPost to: * Send personalised emails to multiple recipients using email API * Track opens and clicks * Analyse statistics around open, clicks, bounce, unsubscribe and spam At an advanced level you can use it to: * Manage multiple sub-accounts which may map to your promotional or transactional sending, multiple product lines or multiple customers * Classify your emails using groups for better analysis * Analyse and fix email sending at sub-account level, IP Pool level or group level * Have automated alerts to notify disruptions regarding email sending * Manage different dedicated IP Pools so to better control your email sending * Automatically know when IP or domain is blacklisted or sender score is down * Leverage pro deliverability tools to get significantly better email deliverability & inboxing > [card] [SendGrid Integration](/guides/sendgrid/overview) > > Connect your SendGrid account to SendPost for unified email management, advanced analytics, and enhanced deliverability monitoring. > [card] [Amazon SES Integration](/guides/amazon-ses/overview) > > Connect your Amazon SES account to SendPost for unified email management, advanced analytics, and enhanced deliverability monitoring. ## Quick Start Get started quickly with our SDKs in your preferred programming language: > [card] [JavaScript](/quickstart/javascript-sdk) > > Get started with JavaScript SDK > [card] [Python](/quickstart/python-sdk) > > Get started with Python SDK > [card] [Golang](/quickstart/golang-sdk) > > Get started with Golang SDK > [card] [Ruby](/quickstart/ruby-sdk) > > Get started with Ruby SDK > [card] [Java](/quickstart/java-sdk) > > Get started with Java SDK > [card] [PHP](/quickstart/php-sdk) > > Get started with PHP SDK ## Common Use Cases Learn how to implement common email sending scenarios: > [card] [Personalize Emails](/api-reference/common-use-cases/personalisation-within-emails) > > Use Handlebars templating to personalize email content with custom fields > [card] [Unsubscribe Links](/api-reference/common-use-cases/adding-unsubscribe-links) > > Add unsubscribe links to emails using built-in template variables > [card] [Custom Headers](/api-reference/common-use-cases/custom-headers) > > Add custom headers to your emails for advanced use cases > [card] [Email Classification](/api-reference/common-use-cases/using-groups-for-email-classification) > > Use groups to classify emails for better analysis and tracking > [card] [Sender Control](/api-reference/common-use-cases/controlling-sender-name-and-email) > > Control sender name and email address for your messages > [card] [Multi-Tenant](/api-reference/common-use-cases/multi-tenant) > > Implement multi-tenant email sending with sub-accounts ## API Reference > [!WARNING] > > Most of the documentation lives in the **API Reference** section. Use the navigation menu or click below to explore all available endpoints and features. > [card] [View API Reference](/api-reference/introduction) > > Complete API documentation with all endpoints, authentication, and examples > [card] [Send Email](/api-reference/email/send-email) > > Learn how to send emails via API ## SDKs We have native SDKs in different programming languages. You can integrate with them or create your own SDK with our API specification. > [card] [Python SDK](https://github.com/sendpost/sendpost-python-sdk) > > View on GitHub > [card] [Golang SDK](https://github.com/sendpost/sendpost-go-sdk) > > View on GitHub > [card] [Ruby SDK](https://github.com/sendpost/sendpost-ruby-sdk) > > View on GitHub > [card] [Java SDK](https://github.com/sendpost/sendpost-java-sdk) > > View on GitHub > [card] [PHP SDK](https://github.com/sendpost/sendpost-php-sdk) > > View on GitHub > [card] [JavaScript SDK](https://github.com/sendpost/sendpost-js-sdk) > > View on GitHub > [!NOTE] > > Need help? Reach out to our team from website chat or email us at [dev@sendpost.io](mailto:dev@sendpost.io) # AWS Lambda Quickstart Source: https://docs.sendpost.io/quickstart/aws-lambda Learn how to send emails with SendPost in AWS Lambda functions using Node.js, Python, and other runtimes ## Prerequisites To get the most out of this guide, you'll need to: * [**Create a SendPost Account**](https://app.sendpost.io/register) * [**AWS Account**](https://aws.amazon.com/) with Lambda access * A **Sub-Account API Key** from your SendPost dashboard > [!NOTE] > > You can find your API keys in your [SendPost Dashboard](https://app.sendpost.io). Make sure to use your Sub-Account API Key for sending emails. ## 1. Node.js Lambda Function ### Install Dependencies Create a `package.json` file: ```json JSON theme={null} { "name": "sendpost-lambda", "version": "1.0.0", "dependencies": { "sendpost-js-sdk": "^1.0.0" } } ``` Install dependencies: ```shellscript npm theme={null} npm install ``` ### Basic Lambda Function Create `index.js`: ```javascript JavaScript theme={null} const sendpost = require('sendpost-js-sdk'); const emailApi = new sendpost.EmailApi(); const API_KEY = process.env.SENDPOST_API_KEY; exports.handler = async (event) => { try { const { to, subject, htmlBody, textBody } = JSON.parse(event.body || event); const emailMessage = new sendpost.EmailMessage(); emailMessage.from = { email: 'hello@playwithsendpost.io', name: 'SendPost' }; emailMessage.to = [{ email: to }]; emailMessage.subject = subject; emailMessage.htmlBody = htmlBody; emailMessage.textBody = textBody || htmlBody.replace(/<[^>]*>/g, ''); emailMessage.trackOpens = true; emailMessage.trackClicks = true; const response = await emailApi.sendEmail(API_KEY, { emailMessage }); return { statusCode: 200, body: JSON.stringify({ success: true, messageId: response.messageId }) }; } catch (error) { console.error('SendPost error:', error); return { statusCode: 500, body: JSON.stringify({ success: false, error: error.message }) }; } }; ``` ### Environment Variables In AWS Lambda Console, add environment variables: * `SENDPOST_API_KEY`: your\_sub\_account\_api\_key ### Deploy with AWS CLI ```bash theme={null} zip -r function.zip index.js node_modules package.json aws lambda update-function-code \ --function-name sendpost-email \ --zip-file fileb://function.zip ``` ## 2. Python Lambda Function ### Install Dependencies Create `requirements.txt`: ```txt theme={null} sendpost-python-sdk ``` ### Basic Lambda Function Create `lambda_function.py`: ```python Python theme={null} import json import os import sendpost_python_sdk from sendpost_python_sdk.api import EmailApi from sendpost_python_sdk.models import EmailMessageObject, EmailAddress, Recipient def lambda_handler(event, context): try: # Parse request body if isinstance(event.get('body'), str): body = json.loads(event['body']) else: body = event to = body.get('to') subject = body.get('subject') html_body = body.get('htmlBody') text_body = body.get('textBody') # Configure SendPost configuration = sendpost_python_sdk.Configuration( host="https://api.sendpost.io/api/v1" ) configuration.api_key['subAccountAuth'] = os.environ['SENDPOST_API_KEY'] with sendpost_python_sdk.ApiClient(configuration) as api_client: email_message = EmailMessageObject() email_message.var_from = EmailAddress( email='hello@playwithsendpost.io', name='SendPost' ) email_message.to = [Recipient(email=to)] email_message.subject = subject email_message.html_body = html_body email_message.text_body = text_body or html_body.replace(r'<[^>]+>', '') email_message.track_opens = True email_message.track_clicks = True response = EmailApi(api_client).send_email(email_message)[0] return { 'statusCode': 200, 'body': json.dumps({ 'success': True, 'messageId': response.message_id }) } except Exception as e: print(f'SendPost error: {str(e)}') return { 'statusCode': 500, 'body': json.dumps({ 'success': False, 'error': str(e) }) } ``` ### Deploy with AWS CLI ```bash theme={null} pip install -r requirements.txt -t . zip -r function.zip lambda_function.py sendpost_python_sdk aws lambda update-function-code \ --function-name sendpost-email-python \ --zip-file fileb://function.zip ``` ## 3. Common Use Cases ### Welcome Email Lambda **Node.js version:** ```javascript JavaScript theme={null} exports.handler = async (event) => { try { const { email, firstName } = JSON.parse(event.body); const emailMessage = new sendpost.EmailMessage(); emailMessage.from = { email: 'hello@playwithsendpost.io', name: 'SendPost' }; emailMessage.to = [{ email, name: firstName, customFields: { firstName } }]; emailMessage.subject = 'Welcome {{firstName}}!'; emailMessage.htmlBody = `

    Welcome, {{firstName}}!

    Thank you for joining us. We're excited to have you on board.

    Unsubscribe

    `; emailMessage.groups = ['welcome']; const response = await emailApi.sendEmail(API_KEY, { emailMessage }); return { statusCode: 200, body: JSON.stringify({ success: true, messageId: response.messageId }) }; } catch (error) { return { statusCode: 500, body: JSON.stringify({ success: false, error: error.message }) }; } }; ``` ### Password Reset Email Lambda **Python version:** ```python Python theme={null} def lambda_handler(event, context): try: body = json.loads(event['body']) if isinstance(event.get('body'), str) else event email = body['email'] reset_token = body['resetToken'] first_name = body.get('firstName', 'User') app_url = os.environ.get('APP_URL', 'https://yourapp.com') reset_url = f"{app_url}/reset-password?token={reset_token}" configuration = sendpost_python_sdk.Configuration( host="https://api.sendpost.io/api/v1" ) configuration.api_key['subAccountAuth'] = os.environ['SENDPOST_API_KEY'] with sendpost_python_sdk.ApiClient(configuration) as api_client: email_message = EmailMessageObject() email_message.var_from = EmailAddress( email='hello@playwithsendpost.io', name='SendPost' ) email_message.to = [Recipient( email=email, name=first_name, custom_fields={ 'firstName': first_name, 'resetUrl': reset_url } )] email_message.subject = 'Reset Your Password' email_message.html_body = f'''

    Hello {{firstName}},

    Click the link below to reset your password:

    Reset Password

    This link expires in 1 hour.

    ''' email_message.groups = ['password-reset'] response = EmailApi(api_client).send_email(email_message)[0] return { 'statusCode': 200, 'body': json.dumps({ 'success': True, 'messageId': response.message_id }) } except Exception as e: return { 'statusCode': 500, 'body': json.dumps({'success': False, 'error': str(e)}) } ``` ## 4. API Gateway Integration ### Create API Gateway Endpoint 1. Create a new API Gateway REST API 2. Create a POST method 3. Set integration type to Lambda Function 4. Select your Lambda function 5. Deploy to a stage ### Example Request ```bash theme={null} curl -X POST https://your-api-id.execute-api.region.amazonaws.com/stage/send-email \ -H "Content-Type: application/json" \ -d '{ "to": "user@example.com", "subject": "Hello from Lambda", "htmlBody": "

    Hello!

    This email was sent from AWS Lambda.

    " }' ``` ## 5. Using Lambda Layers (Node.js) ### Create Layer ```bash theme={null} mkdir -p nodejs/node_modules npm install sendpost-js-sdk --prefix nodejs/ zip -r sendpost-layer.zip nodejs/ aws lambda publish-layer-version \ --layer-name sendpost-sdk \ --zip-file fileb://sendpost-layer.zip \ --compatible-runtimes nodejs18.x nodejs20.x ``` ### Use Layer in Lambda Attach the layer to your Lambda function in the AWS Console or via CLI: ```bash theme={null} aws lambda update-function-configuration \ --function-name sendpost-email \ --layers arn:aws:lambda:region:account:layer:sendpost-sdk:1 ``` ## 6. Error Handling & Logging ### Enhanced Error Handling ```javascript JavaScript theme={null} exports.handler = async (event) => { const requestId = event.requestContext?.requestId || 'unknown'; try { // Validate input if (!event.body) { throw new Error('Request body is required'); } const body = JSON.parse(event.body); if (!body.to || !body.subject || !body.htmlBody) { throw new Error('Missing required fields: to, subject, htmlBody'); } // Send email const response = await emailApi.sendEmail(API_KEY, { emailMessage }); console.log(`Email sent successfully: ${response.messageId}`, { requestId, to: body.to }); return { statusCode: 200, headers: { 'Content-Type': 'application/json', 'X-Request-Id': requestId }, body: JSON.stringify({ success: true, messageId: response.messageId, requestId }) }; } catch (error) { console.error('Lambda error:', { requestId, error: error.message, stack: error.stack }); return { statusCode: error.message.includes('required') ? 400 : 500, headers: { 'Content-Type': 'application/json', 'X-Request-Id': requestId }, body: JSON.stringify({ success: false, error: error.message, requestId }) }; } }; ``` ## 7. Testing Locally ### Using SAM CLI Create `template.yaml`: ```yaml theme={null} AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Resources: SendPostEmailFunction: Type: AWS::Serverless::Function Properties: Handler: index.handler Runtime: nodejs20.x Environment: Variables: SENDPOST_API_KEY: your_api_key Events: SendEmail: Type: Api Properties: Path: /send-email Method: post ``` Test locally: ```bash theme={null} sam local start-api ``` ### Using Lambda Runtime Interface Emulator ```bash theme={null} docker run -p 9000:8080 \ -e SENDPOST_API_KEY=your_api_key \ -v "$PWD":/var/task \ public.ecr.aws/lambda/nodejs:20 ``` Test: ```bash theme={null} curl -X POST "http://localhost:9000/2015-03-31/functions/function/invocations" \ -d '{"body": "{\"to\":\"user@example.com\",\"subject\":\"Test\",\"htmlBody\":\"

    Test

    \"}"}' ``` > [!WARNING] > > Make sure your sender email domain is verified in your SendPost account before sending emails. ## 8. Next Steps Explore more examples and use cases: > [card] [AWS Lambda Documentation](https://docs.aws.amazon.com/lambda/) > > Learn more about AWS Lambda > [card] [SendPost JavaScript SDK](https://www.npmjs.com/package/sendpost-js-sdk) > > View the official SDK package on npm > [card] [SendPost Python SDK](https://pypi.org/project/sendpost-python-sdk/) > > View the official SDK package on PyPI > [card] [Quickstart Example](https://github.com/sendpost/sendpost-aws-lambda-example) > > Complete working example from this quickstart guide # Cloudflare Workers Quickstart Source: https://docs.sendpost.io/quickstart/cloudflare-workers Learn how to send emails with SendPost in Cloudflare Workers using the Fetch API ## Prerequisites To get the most out of this guide, you'll need to: * [**Create a SendPost Account**](https://app.sendpost.io/register) * [**Cloudflare Account**](https://dash.cloudflare.com/sign-up) (free tier works) * [**Wrangler CLI**](https://developers.cloudflare.com/workers/wrangler/) installed * A **Sub-Account API Key** from your SendPost dashboard > [!NOTE] > > You can find your API keys in your [SendPost Dashboard](https://app.sendpost.io). Make sure to use your Sub-Account API Key for sending emails. ## 1. Install Wrangler CLI ```bash theme={null} npm install -g wrangler ``` ## 2. Initialize Worker ```bash theme={null} wrangler init sendpost-email cd sendpost-email ``` ## 3. Basic Email Worker Update `src/index.ts`: ```typescript TypeScript theme={null} export interface Env { SENDPOST_API_KEY: string; } export default { async fetch(request: Request, env: Env): Promise { // Handle CORS if (request.method === 'OPTIONS') { return new Response(null, { headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type', }, }); } if (request.method !== 'POST') { return new Response( JSON.stringify({ error: 'Method not allowed' }), { status: 405, headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, } ); } try { const { to, subject, htmlBody, textBody } = await request.json(); if (!to || !subject || !htmlBody) { return new Response( JSON.stringify({ success: false, error: 'Missing required fields: to, subject, htmlBody', }), { status: 400, headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, } ); } // Prepare email message const emailMessage = { from: { email: 'hello@playwithsendpost.io', name: 'SendPost', }, to: [{ email: to }], subject, htmlBody, textBody: textBody || htmlBody.replace(/<[^>]*>/g, ''), trackOpens: true, trackClicks: true, }; // Send email via SendPost API const response = await fetch('https://api.sendpost.io/api/v1/subaccount/email/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-SubAccount-ApiKey': env.SENDPOST_API_KEY, }, body: JSON.stringify(emailMessage), }); if (!response.ok) { const error = await response.text(); throw new Error(`SendPost API error: ${error}`); } const result = await response.json(); return new Response( JSON.stringify({ success: true, messageId: result.messageId, }), { status: 200, headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, } ); } catch (error: any) { console.error('SendPost error:', error); return new Response( JSON.stringify({ success: false, error: error.message, }), { status: 500, headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, } ); } }, }; ``` ## 4. Configure Worker Update `wrangler.toml`: ```toml theme={null} name = "sendpost-email" main = "src/index.ts" compatibility_date = "2023-10-30" [vars] # Environment variables (use secrets for sensitive data) ``` ## 5. Set Secrets Set the API key as a secret: ```bash theme={null} wrangler secret put SENDPOST_API_KEY ``` Enter your Sub-Account API Key when prompted. ## 6. Deploy Worker Deploy to Cloudflare: ```bash theme={null} wrangler deploy ``` ## 7. Common Use Cases ### Welcome Email Worker Create `src/welcome-email.ts`: ```typescript TypeScript theme={null} export interface Env { SENDPOST_API_KEY: string; } export default { async fetch(request: Request, env: Env): Promise { if (request.method === 'OPTIONS') { return new Response(null, { headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type', }, }); } try { const { email, firstName } = await request.json(); if (!email || !firstName) { return new Response( JSON.stringify({ success: false, error: 'Missing required fields: email, firstName', }), { status: 400, headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, } ); } const emailMessage = { from: { email: 'hello@playwithsendpost.io', name: 'SendPost', }, to: [ { email, name: firstName, customFields: { firstName }, }, ], subject: 'Welcome {{firstName}}!', htmlBody: `

    Welcome, {{firstName}}!

    Thank you for joining us. We're excited to have you on board.

    Get started by exploring our features:

    • Feature 1
    • Feature 2
    • Feature 3

    If you have any questions, just reply to this email.

    Unsubscribe

    `, textBody: ` Welcome, {{firstName}}! Thank you for joining us. We're excited to have you on board. Get started by exploring our features: - Feature 1 - Feature 2 - Feature 3 If you have any questions, just reply to this email. Unsubscribe: {{unsubscribe}} `, groups: ['welcome'], trackOpens: true, trackClicks: true, }; const response = await fetch('https://api.sendpost.io/api/v1/subaccount/email/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-SubAccount-ApiKey': env.SENDPOST_API_KEY, }, body: JSON.stringify(emailMessage), }); const result = await response.json(); return new Response( JSON.stringify({ success: true, messageId: result.messageId, }), { status: 200, headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, } ); } catch (error: any) { return new Response( JSON.stringify({ success: false, error: error.message, }), { status: 500, headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, } ); } }, }; ``` ## 8. Testing Locally Run locally: ```bash theme={null} wrangler dev ``` Test your worker: ```bash theme={null} curl -X POST http://localhost:8787 \ -H "Content-Type: application/json" \ -d '{ "to": "user@example.com", "subject": "Test Email", "htmlBody": "

    Hello from Cloudflare Workers!

    " }' ``` ## 9. Using with Pages Functions If using Cloudflare Pages, create `functions/send-email.ts`: ```typescript TypeScript theme={null} export async function onRequestPost(context: EventContext) { const { request, env } = context; // Same implementation as above } ``` > [!WARNING] > > Make sure your sender email domain is verified in your SendPost account before sending emails. ## 10. Next Steps Explore more examples and use cases: > [card] [Cloudflare Workers](https://developers.cloudflare.com/workers/) > > Learn more about Cloudflare Workers > [card] [Wrangler CLI](https://developers.cloudflare.com/workers/wrangler/) > > Learn more about Wrangler CLI > [card] [Quickstart Example](https://github.com/sendpost/sendpost-cloudflare-workers-example) > > View a complete working example on GitHub # Django Quickstart Source: https://docs.sendpost.io/quickstart/django Learn how to send emails with SendPost in your Django application using custom email backend, views, and signals ## Prerequisites To get the most out of this guide, you'll need to: * [**Create a SendPost Account**](https://app.sendpost.io/register) * [**Django 3.2+**](https://www.djangoproject.com/download/) * [**Python 3.8+**](https://www.python.org/downloads/) * A **Sub-Account API Key** from your SendPost dashboard > [!NOTE] > > You can find your API keys in your [SendPost Dashboard](https://app.sendpost.io). Make sure to use your Sub-Account API Key for sending emails. ## 1. Install Dependencies ```shellscript pip theme={null} pip install sendpost-python-sdk django ``` ## 2. Environment Setup Add to your `settings.py`: ```python Python theme={null} import os from pathlib import Path # Build paths inside the project BASE_DIR = Path(__file__).resolve().parent.parent # SendPost Configuration SENDPOST_API_KEY = os.environ.get('SENDPOST_API_KEY', '') SENDPOST_FROM_EMAIL = os.environ.get('SENDPOST_FROM_EMAIL', 'hello@playwithsendpost.io') SENDPOST_FROM_NAME = os.environ.get('SENDPOST_FROM_NAME', 'SendPost') ``` Create a `.env` file: ```env theme={null} SENDPOST_API_KEY=your_sub_account_api_key SENDPOST_FROM_EMAIL=hello@playwithsendpost.io SENDPOST_FROM_NAME=SendPost ``` ## 3. Create Email Service Create `services/email_service.py`: ```python Python theme={null} import sendpost_python_sdk from sendpost_python_sdk.api import EmailApi from sendpost_python_sdk.models import EmailMessageObject, EmailAddress, Recipient from django.conf import settings import logging logger = logging.getLogger(__name__) class SendPostEmailService: def __init__(self): self.configuration = sendpost_python_sdk.Configuration( host="https://api.sendpost.io/api/v1" ) self.configuration.api_key['subAccountAuth'] = settings.SENDPOST_API_KEY self.from_email = settings.SENDPOST_FROM_EMAIL self.from_name = settings.SENDPOST_FROM_NAME def send_email( self, to, subject, html_body, text_body=None, from_email=None, from_name=None, groups=None, track_opens=True, track_clicks=True, custom_fields=None, ): """ Send an email using SendPost API. Args: to: Email address (str) or list of Recipient objects subject: Email subject html_body: HTML email body text_body: Plain text email body (optional) from_email: Sender email (optional, uses default) from_name: Sender name (optional, uses default) groups: List of groups for email classification track_opens: Enable open tracking track_clicks: Enable click tracking custom_fields: Dict of custom fields for personalization Returns: dict: {'success': bool, 'message_id': str or None, 'error': str or None} """ try: with sendpost_python_sdk.ApiClient(self.configuration) as api_client: email_message = EmailMessageObject() # Set sender email_message.var_from = EmailAddress( email=from_email or self.from_email, name=from_name or self.from_name ) # Handle recipients if isinstance(to, str): recipients = [Recipient(email=to)] elif isinstance(to, list): recipients = [] for recipient in to: if isinstance(recipient, str): recipients.append(Recipient(email=recipient)) elif isinstance(recipient, dict): recipients.append(Recipient( email=recipient.get('email'), name=recipient.get('name'), custom_fields=recipient.get('customFields') or custom_fields )) else: recipients.append(recipient) else: recipients = [Recipient(email=to)] email_message.to = recipients email_message.subject = subject email_message.html_body = html_body email_message.text_body = text_body or self._html_to_text(html_body) email_message.track_opens = track_opens email_message.track_clicks = track_clicks if groups: email_message.groups = groups if isinstance(groups, list) else [groups] response = EmailApi(api_client).send_email(email_message)[0] return { 'success': True, 'message_id': response.message_id, 'data': response } except sendpost_python_sdk.exceptions.ApiException as e: logger.error(f"SendPost API error: {e.status} - {e.body}") return { 'success': False, 'message_id': None, 'error': f"API Error {e.status}: {e.body}" } except Exception as e: logger.error(f"SendPost error: {str(e)}") return { 'success': False, 'message_id': None, 'error': str(e) } def _html_to_text(self, html): """Simple HTML to text conversion""" import re text = re.sub(r'<[^>]+>', '', html) text = text.replace(' ', ' ') text = text.replace('&', '&') text = text.replace('<', '<') text = text.replace('>', '>') return text.strip() # Singleton instance email_service = SendPostEmailService() ``` ## 4. Send Your First Email ### In a View Create `views.py`: ```python Python theme={null} from django.http import JsonResponse from django.views.decorators.http import require_http_methods from django.views.decorators.csrf import csrf_exempt import json from services.email_service import email_service @csrf_exempt @require_http_methods(["POST"]) def send_email_view(request): try: data = json.loads(request.body) to = data.get('to') subject = data.get('subject') html_body = data.get('htmlBody') if not all([to, subject, html_body]): return JsonResponse({ 'success': False, 'error': 'Missing required fields: to, subject, htmlBody' }, status=400) result = email_service.send_email( to=to, subject=subject, html_body=html_body, text_body=data.get('textBody') ) if result['success']: return JsonResponse({ 'success': True, 'messageId': result['message_id'] }) else: return JsonResponse({ 'success': False, 'error': result['error'] }, status=500) except Exception as e: return JsonResponse({ 'success': False, 'error': str(e) }, status=500) ``` Add to `urls.py`: ```python Python theme={null} from django.urls import path from . import views urlpatterns = [ path('api/send-email/', views.send_email_view, name='send_email'), ] ``` ## 5. Common Use Cases ### Welcome Email Create `views/welcome_email.py`: ```python Python theme={null} from services.email_service import email_service from django.http import JsonResponse def send_welcome_email(email, first_name): """Send welcome email to new user""" result = email_service.send_email( to={ 'email': email, 'name': first_name, 'customFields': {'firstName': first_name} }, subject='Welcome {{firstName}}!', html_body='''

    Welcome, {{firstName}}!

    Thank you for joining us. We're excited to have you on board.

    Get started by exploring our features:

    • Feature 1
    • Feature 2
    • Feature 3

    If you have any questions, just reply to this email.

    Unsubscribe

    ''', text_body=''' Welcome, {{firstName}}! Thank you for joining us. We're excited to have you on board. Get started by exploring our features: - Feature 1 - Feature 2 - Feature 3 If you have any questions, just reply to this email. Unsubscribe: {{unsubscribe}} ''', groups=['welcome'] ) return result ``` ### Password Reset Email Create `views/password_reset_email.py`: ```python Python theme={null} from services.email_service import email_service from django.conf import settings def send_password_reset_email(email, reset_token, first_name): """Send password reset email""" reset_url = f"{settings.APP_URL}/reset-password?token={reset_token}" result = email_service.send_email( to={ 'email': email, 'name': first_name, 'customFields': { 'firstName': first_name, 'resetUrl': reset_url } }, subject='Reset Your Password', html_body=f'''

    Hello {{firstName}},

    We received a request to reset your password. Click the button below:

    Reset Password

    Or copy and paste this link: {{resetUrl}}

    This link will expire in 1 hour.

    If you didn't request this, please ignore this email.

    ''', text_body=''' Hello {{firstName}}, We received a request to reset your password. Click the link below: {{resetUrl}} This link will expire in 1 hour. If you didn't request this, please ignore this email. ''', groups=['password-reset'], track_clicks=True ) return result ``` ### Order Confirmation Email Create `views/order_confirmation_email.py`: ```python Python theme={null} from services.email_service import email_service def send_order_confirmation_email(email, first_name, order_id, items, total): """Send order confirmation email""" result = email_service.send_email( to={ 'email': email, 'name': first_name, 'customFields': { 'firstName': first_name, 'orderId': order_id, 'items': items, 'total': f"{total:.2f}" } }, subject='Order {{orderId}} Confirmed', html_body='''

    Thank you for your order, {{firstName}}!

    Your order {{orderId}} has been confirmed.

    Order Details

    {{#each items}} {{/each}}
    Item Quantity Price
    {{name}} {{quantity}} ${{price}}
    Total: ${{total}}

    We'll send you a shipping confirmation once your order is on its way.

    Unsubscribe from order updates

    ''', groups=['order-confirmation'] ) return result ``` ## 6. Using Django Signals Create `signals.py`: ```python Python theme={null} from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User from services.email_service import email_service @receiver(post_save, sender=User) def send_welcome_email_on_user_creation(sender, instance, created, **kwargs): """Send welcome email when a new user is created""" if created and instance.email: email_service.send_email( to={ 'email': instance.email, 'name': instance.first_name or instance.username, 'customFields': { 'firstName': instance.first_name or instance.username } }, subject='Welcome {{firstName}}!', html_body='''

    Welcome, {{firstName}}!

    Thank you for joining us.

    Unsubscribe

    ''', groups=['welcome'] ) ``` Register signals in `apps.py`: ```python Python theme={null} from django.apps import AppConfig class MyAppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'myapp' def ready(self): import myapp.signals # noqa ``` ## 7. Using Celery for Async Email Sending Create `tasks.py`: ```python Python theme={null} from celery import shared_task from services.email_service import email_service import logging logger = logging.getLogger(__name__) @shared_task def send_email_async(to, subject, html_body, text_body=None, **kwargs): """Send email asynchronously using Celery""" try: result = email_service.send_email( to=to, subject=subject, html_body=html_body, text_body=text_body, **kwargs ) return result except Exception as e: logger.error(f"Failed to send email: {str(e)}") raise ``` Use in views: ```python Python theme={null} from .tasks import send_email_async def send_email_view(request): # ... validation code ... # Send asynchronously send_email_async.delay( to=to, subject=subject, html_body=html_body ) return JsonResponse({'success': True, 'message': 'Email queued'}) ``` ## 8. Custom Email Backend (Optional) Create `backends/sendpost_backend.py`: ```python Python theme={null} from django.core.mail.backends.base import BaseEmailBackend from services.email_service import email_service class SendPostEmailBackend(BaseEmailBackend): def send_messages(self, email_messages): """Send email messages using SendPost""" sent_count = 0 for message in email_messages: try: result = email_service.send_email( to=message.to[0] if message.to else None, subject=message.subject, html_body=message.body if hasattr(message, 'alternatives') and message.alternatives else message.body, text_body=message.body if not hasattr(message, 'alternatives') or not message.alternatives else None ) if result['success']: sent_count += 1 except Exception as e: if not self.fail_silently: raise return sent_count ``` Add to `settings.py`: ```python Python theme={null} EMAIL_BACKEND = 'myapp.backends.sendpost_backend.SendPostEmailBackend' ``` > [!WARNING] > > Make sure your sender email domain is verified in your SendPost account before sending emails. ## 9. Next Steps Explore more examples and use cases: > [card] [Django Documentation](https://docs.djangoproject.com/) > > Learn more about Django framework > [card] [SendPost Python SDK](https://pypi.org/project/sendpost-python-sdk/) > > View the official SDK package on PyPI > [card] [Quickstart Example](https://github.com/sendpost/sendpost-django-example) > > View a complete working example on GitHub # Express.js Quickstart Source: https://docs.sendpost.io/quickstart/express Learn how to send emails with SendPost in your Express.js application with route handlers, middleware, and error handling ## Prerequisites To get the most out of this guide, you'll need to: * [**Create a SendPost Account**](https://app.sendpost.io/register) * [**Node.js 14+**](https://nodejs.org/) and [**Express.js**](https://expressjs.com/) * A **Sub-Account API Key** from your SendPost dashboard > [!NOTE] > > You can find your API keys in your [SendPost Dashboard](https://app.sendpost.io). Make sure to use your Sub-Account API Key for sending emails. ## 1. Install Dependencies ```shellscript npm theme={null} npm install express sendpost-js-sdk dotenv ``` ## 2. Environment Setup Create a `.env` file in your project root: ```env theme={null} SENDPOST_API_KEY=your_sub_account_api_key SENDPOST_FROM_EMAIL=hello@playwithsendpost.io SENDPOST_FROM_NAME=SendPost PORT=3000 ``` ## 3. Basic Setup Create `app.js` or `server.js`: ```javascript JavaScript theme={null} require('dotenv').config(); const express = require('express'); const app = express(); app.use(express.json()); app.use(express.urlencoded({ extended: true })); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); }); ``` ## 4. Create Email Service Create `services/emailService.js`: ```javascript JavaScript theme={null} const sendpost = require('sendpost-js-sdk'); const emailApi = new sendpost.EmailApi(); class EmailService { constructor() { this.apiKey = process.env.SENDPOST_API_KEY; this.fromEmail = process.env.SENDPOST_FROM_EMAIL; this.fromName = process.env.SENDPOST_FROM_NAME; } async sendEmail({ to, subject, htmlBody, textBody, from, groups, trackOpens = true, trackClicks = true, customFields, }) { try { const emailMessage = new sendpost.EmailMessage(); emailMessage.from = from || { email: this.fromEmail, name: this.fromName, }; // Handle single email string or array of recipients if (typeof to === 'string') { emailMessage.to = [{ email: to }]; } else { emailMessage.to = to.map(recipient => { if (typeof recipient === 'string') { return { email: recipient }; } return recipient; }); } emailMessage.subject = subject; emailMessage.htmlBody = htmlBody; emailMessage.textBody = textBody || htmlBody.replace(/<[^>]*>/g, ''); emailMessage.trackOpens = trackOpens; emailMessage.trackClicks = trackClicks; if (groups) { emailMessage.groups = Array.isArray(groups) ? groups : [groups]; } const opts = { emailMessage }; const response = await emailApi.sendEmail(this.apiKey, opts); return { success: true, messageId: response.messageId, data: response, }; } catch (error) { console.error('SendPost error:', error); return { success: false, error: error.message || 'Failed to send email', details: error, }; } } } module.exports = new EmailService(); ``` ## 5. Send Your First Email ### Simple Route Handler ```javascript JavaScript theme={null} const emailService = require('./services/emailService'); app.post('/api/send-email', async (req, res) => { try { const { to, subject, htmlBody, textBody } = req.body; if (!to || !subject || !htmlBody) { return res.status(400).json({ success: false, error: 'Missing required fields: to, subject, htmlBody', }); } const result = await emailService.sendEmail({ to, subject, htmlBody, textBody, }); if (result.success) { res.json({ success: true, messageId: result.messageId, }); } else { res.status(500).json({ success: false, error: result.error, }); } } catch (error) { res.status(500).json({ success: false, error: error.message, }); } }); ``` ## 6. Common Use Cases ### Welcome Email Route ```javascript JavaScript theme={null} app.post('/api/welcome-email', async (req, res) => { try { const { email, firstName } = req.body; const result = await emailService.sendEmail({ to: { email, name: firstName, customFields: { firstName }, }, subject: 'Welcome {{firstName}}!', htmlBody: `

    Welcome, {{firstName}}!

    Thank you for joining us. We're excited to have you on board.

    Get started by exploring our features:

    • Feature 1
    • Feature 2
    • Feature 3

    If you have any questions, just reply to this email.

    Unsubscribe

    `, textBody: ` Welcome, {{firstName}}! Thank you for joining us. We're excited to have you on board. Get started by exploring our features: - Feature 1 - Feature 2 - Feature 3 If you have any questions, just reply to this email. Unsubscribe: {{unsubscribe}} `, groups: ['welcome'], }); if (result.success) { res.json({ success: true, messageId: result.messageId }); } else { res.status(500).json({ success: false, error: result.error }); } } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); ``` ### Password Reset Email ```javascript JavaScript theme={null} app.post('/api/password-reset', async (req, res) => { try { const { email, resetToken, firstName } = req.body; const resetUrl = `${process.env.APP_URL}/reset-password?token=${resetToken}`; const result = await emailService.sendEmail({ to: { email, name: firstName, customFields: { firstName, resetUrl, }, }, subject: 'Reset Your Password', htmlBody: `

    Hello {{firstName}},

    We received a request to reset your password. Click the button below to create a new password:

    Reset Password

    Or copy and paste this link into your browser:

    {{resetUrl}}

    This link will expire in 1 hour.

    If you didn't request this, please ignore this email.

    `, textBody: ` Hello {{firstName}}, We received a request to reset your password. Click the link below: {{resetUrl}} This link will expire in 1 hour. If you didn't request this, please ignore this email. `, groups: ['password-reset'], trackClicks: true, }); if (result.success) { res.json({ success: true, messageId: result.messageId }); } else { res.status(500).json({ success: false, error: result.error }); } } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); ``` ### Order Confirmation Email ```javascript JavaScript theme={null} app.post('/api/order-confirmation', async (req, res) => { try { const { email, firstName, orderId, items, total } = req.body; const result = await emailService.sendEmail({ to: { email, name: firstName, customFields: { firstName, orderId, items, total: total.toFixed(2), }, }, subject: 'Order {{orderId}} Confirmed', htmlBody: `

    Thank you for your order, {{firstName}}!

    Your order {{orderId}} has been confirmed.

    Order Details

    {{#each items}} {{/each}}
    Item Quantity Price
    {{name}} {{quantity}} ${{price}}
    Total: ${{total}}

    We'll send you a shipping confirmation once your order is on its way.

    Unsubscribe from order updates

    `, groups: ['order-confirmation'], }); if (result.success) { res.json({ success: true, messageId: result.messageId }); } else { res.status(500).json({ success: false, error: result.error }); } } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); ``` ## 7. Using Middleware for Email Routes Create `middleware/emailValidation.js`: ```javascript JavaScript theme={null} const validateEmailRequest = (req, res, next) => { const { to, subject, htmlBody } = req.body; if (!to) { return res.status(400).json({ success: false, error: 'Recipient email (to) is required', }); } if (!subject) { return res.status(400).json({ success: false, error: 'Email subject is required', }); } if (!htmlBody) { return res.status(400).json({ success: false, error: 'Email HTML body is required', }); } // Validate email format const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; const emails = Array.isArray(to) ? to : [to]; for (const email of emails) { const emailAddress = typeof email === 'string' ? email : email.email; if (!emailRegex.test(emailAddress)) { return res.status(400).json({ success: false, error: `Invalid email format: ${emailAddress}`, }); } } next(); }; module.exports = { validateEmailRequest }; ``` Use the middleware: ```javascript JavaScript theme={null} const { validateEmailRequest } = require('./middleware/emailValidation'); app.post('/api/send-email', validateEmailRequest, async (req, res) => { // ... email sending logic }); ``` ## 8. Error Handling Middleware ```javascript JavaScript theme={null} const errorHandler = (err, req, res, next) => { console.error('Error:', err); if (err.name === 'ValidationError') { return res.status(400).json({ success: false, error: err.message, }); } res.status(500).json({ success: false, error: 'Internal server error', message: process.env.NODE_ENV === 'development' ? err.message : undefined, }); }; app.use(errorHandler); ``` ## 9. Batch Email Sending ```javascript JavaScript theme={null} app.post('/api/send-batch', async (req, res) => { try { const { recipients, subject, htmlBody, textBody } = req.body; if (!recipients || !Array.isArray(recipients) || recipients.length === 0) { return res.status(400).json({ success: false, error: 'Recipients array is required', }); } // SendPost supports up to 500 recipients per request if (recipients.length > 500) { return res.status(400).json({ success: false, error: 'Maximum 500 recipients per request', }); } const result = await emailService.sendEmail({ to: recipients, subject, htmlBody, textBody, }); if (result.success) { res.json({ success: true, messageId: result.messageId, recipientsCount: recipients.length, }); } else { res.status(500).json({ success: false, error: result.error, }); } } catch (error) { res.status(500).json({ success: false, error: error.message, }); } }); ``` > [!WARNING] > > Make sure your sender email domain is verified in your SendPost account before sending emails. ## 10. Next Steps Explore more examples and use cases: > [card] [Express.js Documentation](https://expressjs.com/) > > Learn more about Express.js framework > [card] [SendPost JavaScript SDK](https://www.npmjs.com/package/sendpost-js-sdk) > > View the official SDK package on npm > [card] [Quickstart Example](https://github.com/sendpost/sendpost-express-example) > > View a complete working example on GitHub # FastAPI Quickstart Source: https://docs.sendpost.io/quickstart/fastapi Learn how to send emails with SendPost in your FastAPI application using async endpoints, dependency injection, and Pydantic models ## Prerequisites To get the most out of this guide, you'll need to: * [**Create a SendPost Account**](https://app.sendpost.io/register) * [**FastAPI 0.100+**](https://fastapi.tiangolo.com/) * [**Python 3.8+**](https://www.python.org/downloads/) * A **Sub-Account API Key** from your SendPost dashboard > [!NOTE] > > You can find your API keys in your [SendPost Dashboard](https://app.sendpost.io). Make sure to use your Sub-Account API Key for sending emails. ## 1. Install Dependencies ```shellscript pip theme={null} pip install fastapi uvicorn sendpost-python-sdk python-dotenv pydantic ``` ## 2. Environment Setup Create a `.env` file: ```env theme={null} SENDPOST_API_KEY=your_sub_account_api_key SENDPOST_FROM_EMAIL=hello@playwithsendpost.io SENDPOST_FROM_NAME=SendPost ``` ## 3. Basic FastAPI App Setup Create `main.py`: ```python Python theme={null} from fastapi import FastAPI from dotenv import load_dotenv import os load_dotenv() app = FastAPI(title="SendPost Email API") @app.get("/") def read_root(): return {"message": "SendPost Email API"} ``` ## 4. Create Email Service Create `services/email_service.py`: ```python Python theme={null} import sendpost_python_sdk from sendpost_python_sdk.api import EmailApi from sendpost_python_sdk.models import EmailMessageObject, EmailAddress, Recipient import os import re from typing import List, Dict, Any, Optional, Union class SendPostEmailService: def __init__(self): self.api_key = os.getenv('SENDPOST_API_KEY') self.from_email = os.getenv('SENDPOST_FROM_EMAIL') self.from_name = os.getenv('SENDPOST_FROM_NAME') self.configuration = sendpost_python_sdk.Configuration( host="https://api.sendpost.io/api/v1" ) self.configuration.api_key['subAccountAuth'] = self.api_key async def send_email( self, to: Union[str, List[Union[str, Dict[str, Any]]]], subject: str, html_body: str, text_body: Optional[str] = None, from_email: Optional[str] = None, from_name: Optional[str] = None, groups: Optional[List[str]] = None, track_opens: bool = True, track_clicks: bool = True, custom_fields: Optional[Dict[str, Any]] = None, ) -> Dict[str, Any]: """ Send an email using SendPost API. Args: to: Email address (str) or list of Recipient objects/dicts subject: Email subject html_body: HTML email body text_body: Plain text email body (optional) from_email: Sender email (optional) from_name: Sender name (optional) groups: List of groups for email classification track_opens: Enable open tracking track_clicks: Enable click tracking custom_fields: Dict of custom fields for personalization Returns: dict: {'success': bool, 'message_id': str or None, 'error': str or None} """ try: with sendpost_python_sdk.ApiClient(self.configuration) as api_client: email_message = EmailMessageObject() # Set sender email_message.var_from = EmailAddress( email=from_email or self.from_email, name=from_name or self.from_name ) # Handle recipients if isinstance(to, str): recipients = [Recipient(email=to)] elif isinstance(to, list): recipients = [] for recipient in to: if isinstance(recipient, str): recipients.append(Recipient(email=recipient)) elif isinstance(recipient, dict): recipients.append(Recipient( email=recipient.get('email'), name=recipient.get('name'), custom_fields=recipient.get('customFields') or custom_fields )) else: recipients.append(recipient) else: recipients = [Recipient(email=to)] email_message.to = recipients email_message.subject = subject email_message.html_body = html_body email_message.text_body = text_body or self._html_to_text(html_body) email_message.track_opens = track_opens email_message.track_clicks = track_clicks if groups: email_message.groups = groups response = EmailApi(api_client).send_email(email_message)[0] return { 'success': True, 'message_id': response.message_id, 'data': response } except sendpost_python_sdk.exceptions.ApiException as e: return { 'success': False, 'message_id': None, 'error': f"API Error {e.status}: {e.body}" } except Exception as e: return { 'success': False, 'message_id': None, 'error': str(e) } @staticmethod def _html_to_text(html: str) -> str: """Simple HTML to text conversion""" text = re.sub(r'<[^>]+>', '', html) text = text.replace(' ', ' ') text = text.replace('&', '&') text = text.replace('<', '<') text = text.replace('>', '>') return text.strip() # Singleton instance email_service = SendPostEmailService() ``` ## 5. Create Pydantic Models Create `models/email.py`: ```python Python theme={null} from pydantic import BaseModel, EmailStr, Field from typing import List, Optional, Dict, Any, Union class EmailRecipient(BaseModel): email: EmailStr name: Optional[str] = None customFields: Optional[Dict[str, Any]] = None class SendEmailRequest(BaseModel): to: Union[EmailStr, List[EmailRecipient]] subject: str = Field(..., min_length=1) htmlBody: str = Field(..., min_length=1) textBody: Optional[str] = None from_email: Optional[EmailStr] = Field(None, alias='from') from_name: Optional[str] = None groups: Optional[List[str]] = None trackOpens: bool = True trackClicks: bool = True class EmailResponse(BaseModel): success: bool messageId: Optional[str] = None error: Optional[str] = None class WelcomeEmailRequest(BaseModel): email: EmailStr firstName: str = Field(..., min_length=1) class PasswordResetRequest(BaseModel): email: EmailStr resetToken: str = Field(..., min_length=1) firstName: Optional[str] = 'User' ``` ## 6. Send Your First Email ### Basic Endpoint ```python Python theme={null} from fastapi import FastAPI, HTTPException from models.email import SendEmailRequest, EmailResponse from services.email_service import email_service app = FastAPI() @app.post("/api/send-email", response_model=EmailResponse) async def send_email(request: SendEmailRequest): """Send an email using SendPost""" result = await email_service.send_email( to=request.to, subject=request.subject, html_body=request.htmlBody, text_body=request.textBody, from_email=request.from_email, from_name=request.from_name, groups=request.groups, track_opens=request.trackOpens, track_clicks=request.trackClicks ) if result['success']: return EmailResponse( success=True, messageId=result['message_id'] ) else: raise HTTPException( status_code=500, detail=result['error'] ) ``` ## 7. Common Use Cases ### Welcome Email Endpoint ```python Python theme={null} from models.email import WelcomeEmailRequest, EmailResponse @app.post("/api/welcome-email", response_model=EmailResponse) async def send_welcome_email(request: WelcomeEmailRequest): """Send welcome email to new user""" result = await email_service.send_email( to={ 'email': request.email, 'name': request.firstName, 'customFields': {'firstName': request.firstName} }, subject='Welcome {{firstName}}!', html_body='''

    Welcome, {{firstName}}!

    Thank you for joining us. We're excited to have you on board.

    Get started by exploring our features:

    • Feature 1
    • Feature 2
    • Feature 3

    If you have any questions, just reply to this email.

    Unsubscribe

    ''', text_body=''' Welcome, {{firstName}}! Thank you for joining us. We're excited to have you on board. Get started by exploring our features: - Feature 1 - Feature 2 - Feature 3 If you have any questions, just reply to this email. Unsubscribe: {{unsubscribe}} ''', groups=['welcome'] ) if result['success']: return EmailResponse( success=True, messageId=result['message_id'] ) else: raise HTTPException( status_code=500, detail=result['error'] ) ``` ### Password Reset Email ```python Python theme={null} from models.email import PasswordResetRequest from fastapi import Request @app.post("/api/password-reset", response_model=EmailResponse) async def send_password_reset(request: Request, data: PasswordResetRequest): """Send password reset email""" base_url = str(request.base_url).rstrip('/') reset_url = f"{base_url}/reset-password?token={data.resetToken}" result = await email_service.send_email( to={ 'email': data.email, 'name': data.firstName, 'customFields': { 'firstName': data.firstName, 'resetUrl': reset_url } }, subject='Reset Your Password', html_body=f'''

    Hello {{firstName}},

    We received a request to reset your password. Click the button below:

    Reset Password

    Or copy and paste this link: {{resetUrl}}

    This link will expire in 1 hour.

    If you didn't request this, please ignore this email.

    ''', text_body=''' Hello {{firstName}}, We received a request to reset your password. Click the link below: {{resetUrl}} This link will expire in 1 hour. If you didn't request this, please ignore this email. ''', groups=['password-reset'], track_clicks=True ) if result['success']: return EmailResponse( success=True, messageId=result['message_id'] ) else: raise HTTPException( status_code=500, detail=result['error'] ) ``` ## 8. Using Dependency Injection Create `dependencies.py`: ```python Python theme={null} from fastapi import Depends from services.email_service import SendPostEmailService def get_email_service() -> SendPostEmailService: """Dependency to get email service instance""" return SendPostEmailService() # Or use a singleton from services.email_service import email_service def get_email_service() -> SendPostEmailService: return email_service ``` Use in endpoints: ```python Python theme={null} from dependencies import get_email_service @app.post("/api/send-email") async def send_email( request: SendEmailRequest, email_service: SendPostEmailService = Depends(get_email_service) ): result = await email_service.send_email( to=request.to, subject=request.subject, html_body=request.htmlBody ) # ... rest of the code ``` ## 9. Background Tasks Use FastAPI's BackgroundTasks for async email sending: ```python Python theme={null} from fastapi import BackgroundTasks @app.post("/api/send-email-async") async def send_email_async( request: SendEmailRequest, background_tasks: BackgroundTasks ): """Queue email to be sent in background""" background_tasks.add_task( email_service.send_email, to=request.to, subject=request.subject, html_body=request.htmlBody, text_body=request.textBody ) return {"success": True, "message": "Email queued for sending"} ``` ## 10. Error Handling Create `exceptions.py`: ```python Python theme={null} from fastapi import HTTPException class EmailSendException(HTTPException): def __init__(self, detail: str): super().__init__(status_code=500, detail=detail) class InvalidEmailException(HTTPException): def __init__(self, detail: str = "Invalid email address"): super().__init__(status_code=400, detail=detail) ``` Use in endpoints: ```python Python theme={null} from exceptions import EmailSendException @app.post("/api/send-email") async def send_email(request: SendEmailRequest): result = await email_service.send_email( to=request.to, subject=request.subject, html_body=request.htmlBody ) if not result['success']: raise EmailSendException(result['error']) return EmailResponse( success=True, messageId=result['message_id'] ) ``` ## 11. Running the Application ```shellscript Shell theme={null} uvicorn main:app --reload ``` The API will be available at `http://localhost:8000` API documentation (Swagger UI) will be available at `http://localhost:8000/docs` > [!WARNING] > > Make sure your sender email domain is verified in your SendPost account before sending emails. ## 12. Next Steps Explore more examples and use cases: > [card] [FastAPI Documentation](https://fastapi.tiangolo.com/) > > Learn more about FastAPI framework > [card] [SendPost Python SDK](https://pypi.org/project/sendpost-python-sdk/) > > View the official SDK package on PyPI > [card] [Quickstart Example](https://github.com/sendpost/sendpost-fastapi-example) > > View a complete working example on GitHub # Flask Quickstart Source: https://docs.sendpost.io/quickstart/flask Learn how to send emails with SendPost in your Flask application using blueprints, utilities, and error handling ## Prerequisites To get the most out of this guide, you'll need to: * [**Create a SendPost Account**](https://app.sendpost.io/register) * [**Flask 2.0+**](https://flask.palletsprojects.com/) * [**Python 3.8+**](https://www.python.org/downloads/) * A **Sub-Account API Key** from your SendPost dashboard > [!NOTE] > > You can find your API keys in your [SendPost Dashboard](https://app.sendpost.io). Make sure to use your Sub-Account API Key for sending emails. ## 1. Install Dependencies ```shellscript pip theme={null} pip install flask sendpost-python-sdk python-dotenv ``` ## 2. Environment Setup Create a `.env` file: ```env theme={null} SENDPOST_API_KEY=your_sub_account_api_key SENDPOST_FROM_EMAIL=hello@playwithsendpost.io SENDPOST_FROM_NAME=SendPost FLASK_ENV=development ``` ## 3. Basic Flask App Setup Create `app.py`: ```python Python theme={null} from flask import Flask from dotenv import load_dotenv import os load_dotenv() app = Flask(__name__) app.config['SENDPOST_API_KEY'] = os.getenv('SENDPOST_API_KEY') app.config['SENDPOST_FROM_EMAIL'] = os.getenv('SENDPOST_FROM_EMAIL') app.config['SENDPOST_FROM_NAME'] = os.getenv('SENDPOST_FROM_NAME') if __name__ == '__main__': app.run(debug=True) ``` ## 4. Create Email Utility Create `utils/email_service.py`: ```python Python theme={null} import sendpost_python_sdk from sendpost_python_sdk.api import EmailApi from sendpost_python_sdk.models import EmailMessageObject, EmailAddress, Recipient from flask import current_app import re class SendPostEmailService: @staticmethod def send_email( to, subject, html_body, text_body=None, from_email=None, from_name=None, groups=None, track_opens=True, track_clicks=True, custom_fields=None, ): """ Send an email using SendPost API. Args: to: Email address (str) or list of Recipient objects/dicts subject: Email subject html_body: HTML email body text_body: Plain text email body (optional) from_email: Sender email (optional) from_name: Sender name (optional) groups: List of groups for email classification track_opens: Enable open tracking track_clicks: Enable click tracking custom_fields: Dict of custom fields for personalization Returns: dict: {'success': bool, 'message_id': str or None, 'error': str or None} """ try: configuration = sendpost_python_sdk.Configuration( host="https://api.sendpost.io/api/v1" ) configuration.api_key['subAccountAuth'] = current_app.config['SENDPOST_API_KEY'] with sendpost_python_sdk.ApiClient(configuration) as api_client: email_message = EmailMessageObject() # Set sender email_message.var_from = EmailAddress( email=from_email or current_app.config['SENDPOST_FROM_EMAIL'], name=from_name or current_app.config['SENDPOST_FROM_NAME'] ) # Handle recipients if isinstance(to, str): recipients = [Recipient(email=to)] elif isinstance(to, list): recipients = [] for recipient in to: if isinstance(recipient, str): recipients.append(Recipient(email=recipient)) elif isinstance(recipient, dict): recipients.append(Recipient( email=recipient.get('email'), name=recipient.get('name'), custom_fields=recipient.get('customFields') or custom_fields )) else: recipients.append(recipient) else: recipients = [Recipient(email=to)] email_message.to = recipients email_message.subject = subject email_message.html_body = html_body email_message.text_body = text_body or SendPostEmailService._html_to_text(html_body) email_message.track_opens = track_opens email_message.track_clicks = track_clicks if groups: email_message.groups = groups if isinstance(groups, list) else [groups] response = EmailApi(api_client).send_email(email_message)[0] return { 'success': True, 'message_id': response.message_id, 'data': response } except sendpost_python_sdk.exceptions.ApiException as e: current_app.logger.error(f"SendPost API error: {e.status} - {e.body}") return { 'success': False, 'message_id': None, 'error': f"API Error {e.status}: {e.body}" } except Exception as e: current_app.logger.error(f"SendPost error: {str(e)}") return { 'success': False, 'message_id': None, 'error': str(e) } @staticmethod def _html_to_text(html): """Simple HTML to text conversion""" text = re.sub(r'<[^>]+>', '', html) text = text.replace(' ', ' ') text = text.replace('&', '&') text = text.replace('<', '<') text = text.replace('>', '>') return text.strip() ``` ## 5. Send Your First Email ### Simple Route ```python Python theme={null} from flask import Flask, request, jsonify from utils.email_service import SendPostEmailService app = Flask(__name__) @app.route('/api/send-email', methods=['POST']) def send_email(): try: data = request.get_json() to = data.get('to') subject = data.get('subject') html_body = data.get('htmlBody') if not all([to, subject, html_body]): return jsonify({ 'success': False, 'error': 'Missing required fields: to, subject, htmlBody' }), 400 result = SendPostEmailService.send_email( to=to, subject=subject, html_body=html_body, text_body=data.get('textBody') ) if result['success']: return jsonify({ 'success': True, 'messageId': result['message_id'] }) else: return jsonify({ 'success': False, 'error': result['error'] }), 500 except Exception as e: return jsonify({ 'success': False, 'error': str(e) }), 500 ``` ## 6. Common Use Cases ### Welcome Email Route ```python Python theme={null} @app.route('/api/welcome-email', methods=['POST']) def send_welcome_email(): try: data = request.get_json() email = data.get('email') first_name = data.get('firstName') if not email or not first_name: return jsonify({ 'success': False, 'error': 'Missing required fields: email, firstName' }), 400 result = SendPostEmailService.send_email( to={ 'email': email, 'name': first_name, 'customFields': {'firstName': first_name} }, subject='Welcome {{firstName}}!', html_body='''

    Welcome, {{firstName}}!

    Thank you for joining us. We're excited to have you on board.

    Get started by exploring our features:

    • Feature 1
    • Feature 2
    • Feature 3

    If you have any questions, just reply to this email.

    Unsubscribe

    ''', text_body=''' Welcome, {{firstName}}! Thank you for joining us. We're excited to have you on board. Get started by exploring our features: - Feature 1 - Feature 2 - Feature 3 If you have any questions, just reply to this email. Unsubscribe: {{unsubscribe}} ''', groups=['welcome'] ) if result['success']: return jsonify({ 'success': True, 'messageId': result['message_id'] }) else: return jsonify({ 'success': False, 'error': result['error'] }), 500 except Exception as e: return jsonify({ 'success': False, 'error': str(e) }), 500 ``` ### Password Reset Email ```python Python theme={null} @app.route('/api/password-reset', methods=['POST']) def send_password_reset(): try: data = request.get_json() email = data.get('email') reset_token = data.get('resetToken') first_name = data.get('firstName', 'User') if not email or not reset_token: return jsonify({ 'success': False, 'error': 'Missing required fields: email, resetToken' }), 400 reset_url = f"{request.host_url}reset-password?token={reset_token}" result = SendPostEmailService.send_email( to={ 'email': email, 'name': first_name, 'customFields': { 'firstName': first_name, 'resetUrl': reset_url } }, subject='Reset Your Password', html_body='''

    Hello {{firstName}},

    We received a request to reset your password. Click the button below:

    Reset Password

    Or copy and paste this link: {{resetUrl}}

    This link will expire in 1 hour.

    If you didn't request this, please ignore this email.

    ''', text_body=''' Hello {{firstName}}, We received a request to reset your password. Click the link below: {{resetUrl}} This link will expire in 1 hour. If you didn't request this, please ignore this email. ''', groups=['password-reset'], track_clicks=True ) if result['success']: return jsonify({ 'success': True, 'messageId': result['message_id'] }) else: return jsonify({ 'success': False, 'error': result['error'] }), 500 except Exception as e: return jsonify({ 'success': False, 'error': str(e) }), 500 ``` ## 7. Using Blueprints Create `blueprints/email_bp.py`: ```python Python theme={null} from flask import Blueprint, request, jsonify from utils.email_service import SendPostEmailService email_bp = Blueprint('email', __name__, url_prefix='/api/email') @email_bp.route('/send', methods=['POST']) def send_email(): """Send a basic email""" try: data = request.get_json() to = data.get('to') subject = data.get('subject') html_body = data.get('htmlBody') if not all([to, subject, html_body]): return jsonify({ 'success': False, 'error': 'Missing required fields: to, subject, htmlBody' }), 400 result = SendPostEmailService.send_email( to=to, subject=subject, html_body=html_body, text_body=data.get('textBody') ) if result['success']: return jsonify({ 'success': True, 'messageId': result['message_id'] }) else: return jsonify({ 'success': False, 'error': result['error'] }), 500 except Exception as e: return jsonify({ 'success': False, 'error': str(e) }), 500 @email_bp.route('/welcome', methods=['POST']) def welcome_email(): """Send welcome email""" # ... implementation similar to above ... pass @email_bp.route('/password-reset', methods=['POST']) def password_reset_email(): """Send password reset email""" # ... implementation similar to above ... pass ``` Register in `app.py`: ```python Python theme={null} from blueprints.email_bp import email_bp app.register_blueprint(email_bp) ``` ## 8. Error Handling Create `errors.py`: ```python Python theme={null} from flask import jsonify from werkzeug.exceptions import HTTPException def register_error_handlers(app): @app.errorhandler(400) def bad_request(error): return jsonify({ 'success': False, 'error': 'Bad request', 'message': str(error) }), 400 @app.errorhandler(500) def internal_error(error): return jsonify({ 'success': False, 'error': 'Internal server error', 'message': str(error) if app.debug else 'An error occurred' }), 500 @app.errorhandler(Exception) def handle_exception(e): if isinstance(e, HTTPException): return e app.logger.error(f"Unhandled exception: {str(e)}") return jsonify({ 'success': False, 'error': 'Internal server error', 'message': str(e) if app.debug else 'An error occurred' }), 500 ``` Use in `app.py`: ```python Python theme={null} from errors import register_error_handlers register_error_handlers(app) ``` ## 9. Using Flask-Mail Style Interface (Optional) Create `extensions/email.py`: ```python Python theme={null} from flask import current_app from utils.email_service import SendPostEmailService class Message: def __init__(self, subject, recipients, body, html=None, sender=None): self.subject = subject self.recipients = recipients if isinstance(recipients, list) else [recipients] self.body = body self.html = html self.sender = sender class Mail: def __init__(self, app=None): self.app = app if app is not None: self.init_app(app) def init_app(self, app): self.app = app def send(self, message): """Send email message using SendPost""" html_body = message.html or message.body text_body = message.body if message.html else None result = SendPostEmailService.send_email( to=message.recipients, subject=message.subject, html_body=html_body, text_body=text_body, from_email=message.sender ) if not result['success']: raise Exception(result['error']) return result ``` Use it: ```python Python theme={null} from extensions.email import Mail, Message mail = Mail() @app.route('/send') def send(): msg = Message( subject='Hello', recipients=['user@example.com'], body='Plain text body', html='

    HTML body

    ' ) mail.send(msg) return 'Email sent!' ``` > [!WARNING] > > Make sure your sender email domain is verified in your SendPost account before sending emails. ## 10. Next Steps Explore more examples and use cases: > [card] [Flask Documentation](https://flask.palletsprojects.com/) > > Learn more about Flask framework > [card] [SendPost Python SDK](https://pypi.org/project/sendpost-python-sdk/) > > View the official SDK package on PyPI > [card] [Quickstart Example](https://github.com/sendpost/sendpost-flask-example) > > View a complete working example on GitHub # Golang SDK Quickstart Source: https://docs.sendpost.io/quickstart/golang-sdk Learn how to configure and send your first email with SendPost Golang SDK ## Prerequisites To get the most out of this guide, you'll need to: * [**Create a SendPost Account**](https://app.sendpost.io/register) * [**Install GoLang >v1.19.0**](https://go.dev/doc/install) * A **Sub-Account API Key** from your SendPost dashboard > [!NOTE] > > You can find your API keys in your [SendPost > Dashboard](https://app.sendpost.io). Make sure to use your Sub-Account API Key > for sending emails. ## 1. Install ```shellscript Shell theme={null} go get github.com/sendpost/sendpost_go_sdk ``` ## 2. Getting Started ```go Go theme={null} package main import ( "fmt" "os" sendpost "github.com/sendpost/sendpost_go_sdk" ) func main() { cfg := sendpost.NewConfiguration() client := sendpost.NewAPIClient(cfg) emailMessage := sendpost.EmailMessage{} emailMessage.SetSubject("Hello World") emailMessage.SetHtmlBody("it works!") emailMessage.From = &sendpost.From{} emailMessage.From.SetEmail("hello@playwithsendpost.io") tos := make([]sendpost.To, 0) to := &sendpost.To{} to.SetEmail("gavin@hooli.com") tos = append(tos, *to) emailMessage.To = tos emailRequest := sendpost.ApiSendEmailRequest{} emailRequest = emailRequest.XSubAccountApiKey("your_api_key") emailRequest = emailRequest.EmailMessage(emailMessage) res, _, err := client.EmailApi.SendEmailExecute(emailRequest) if err != nil { fmt.Fprintf(os.Stderr, "Error when calling EmailApi->SendEmail: %v\n", err) return } fmt.Fprintf(os.Stdout, "Response: %v\n", res) } ``` > [!WARNING] > > Make sure your sender email domain is verified in your SendPost account before > sending emails. ## 3. Next Steps Explore more examples and use cases: > [card] [Golang SDK](https://github.com/sendpost/sendpost_go_sdk) > > View the official SDK on GitHub > [card] [SDK Examples](https://github.com/sendpost/sendpost-examples-go) > > Comprehensive email sending examples > [card] [ESP Workflow Example](https://github.com/sendpost/go-esp-example) > > Full-featured example app with comprehensive ESP workflow # Java SDK Quickstart Source: https://docs.sendpost.io/quickstart/java-sdk Learn how to configure and send your first email with SendPost Java SDK ## Prerequisites To get the most out of this guide, you'll need to: * [**Create a SendPost Account**](https://app.sendpost.io/register) * [Install Java 1.8+](https://www.oracle.com/java/technologies/downloads/?er=221886) * [Install Maven (3.8.3+)/Gradle (7.2+)](https://maven.apache.org/download.cgi) * A **Sub-Account API Key** from your SendPost dashboard > [!NOTE] > > You can find your API keys in your [SendPost > Dashboard](https://app.sendpost.io). Make sure to use your Sub-Account API Key > for sending emails. ## 1. Install > [!NOTE] > > Check [Maven Central](https://central.sonatype.com/artifact/io.sendpost/sendpost-java-sdk) for the latest version. ### Maven Setup #### Option 1: Standard Maven Project Add this dependency to your `pom.xml`: ```xml POM theme={null} 4.0.0 com.example sendpost-example 1.0-SNAPSHOT 1.8 1.8 UTF-8 io.sendpost sendpost-java-sdk 1.1.4 ``` #### Option 2: Spring Boot with Maven Add to your `pom.xml`: ```xml POM theme={null} org.springframework.boot spring-boot-starter-web io.sendpost sendpost-java-sdk 1.1.4 ``` ### Gradle Setup #### Option 1: Standard Gradle Project Add to your `build.gradle`: ```groovy Gradle theme={null} plugins { id 'java' } repositories { mavenCentral() } dependencies { implementation 'io.sendpost:sendpost-java-sdk:1.1.4' } java { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } ``` #### Option 2: Spring Boot with Gradle Add to your `build.gradle`: ```groovy Gradle theme={null} plugins { id 'org.springframework.boot' version '2.7.0' id 'io.spring.dependency-management' version '1.0.11.RELEASE' id 'java' } repositories { mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'io.sendpost:sendpost-java-sdk:1.1.4' } java { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } ``` #### Option 3: Gradle with Kotlin DSL Add to your `build.gradle.kts`: ```kotlin Kotlin theme={null} plugins { java } repositories { mavenCentral() } dependencies { implementation("io.sendpost:sendpost-java-sdk:1.1.4") } java { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } ``` ## 2. Getting Started ### Basic Example ```java Java theme={null} import io.sendpost.client.ApiClient; import io.sendpost.client.ApiException; import io.sendpost.client.Configuration; import io.sendpost.client.api.EmailApi; import io.sendpost.client.model.*; import java.util.Arrays; import java.util.List; public class SendPostExample { public static void main(String[] args) { // Configure API client ApiClient defaultClient = Configuration.getDefaultApiClient(); defaultClient.setBasePath("https://api.sendpost.io/api/v1"); EmailApi apiInstance = new EmailApi(defaultClient); String apiKey = System.getenv("SENDPOST_API_KEY"); // Sub-Account API Key // Create email message EmailMessage emailMessage = new EmailMessage(); emailMessage.setSubject("Hello World"); emailMessage.setHtmlBody("it works!"); emailMessage.setTextBody("it works!"); // Set sender From from = new From(); from.setEmail("hello@playwithsendpost.io"); from.setName("SendPost"); emailMessage.setFrom(from); // Set recipient To to = new To(); to.setEmail("user@example.com"); emailMessage.setTo(Arrays.asList(to)); // Enable tracking emailMessage.setTrackOpens(true); emailMessage.setTrackClicks(true); try { List result = apiInstance.sendEmail(apiKey, emailMessage); System.out.println("Email sent successfully!"); System.out.println("Message ID: " + result.get(0).getMessageId()); } catch (ApiException e) { System.err.println("Exception when calling EmailApi#sendEmail"); System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); System.err.println("Response headers: " + e.getResponseHeaders()); e.printStackTrace(); } } } ``` ### Maven Project Structure ``` sendpost-example/ ├── pom.xml └── src/ └── main/ └── java/ └── com/ └── example/ └── SendPostExample.java ``` **Run with Maven:** ```bash theme={null} mvn compile exec:java -Dexec.mainClass="com.example.SendPostExample" ``` ### Gradle Project Structure ``` sendpost-example/ ├── build.gradle └── src/ └── main/ └── java/ └── com/ └── example/ └── SendPostExample.java ``` **Run with Gradle:** ```bash theme={null} ./gradlew run --main-class=com.example.SendPostExample ``` Or add to `build.gradle`: ```groovy Gradle theme={null} application { mainClass = 'com.example.SendPostExample' } ``` Then run: ```bash theme={null} ./gradlew run ``` ## 3. Common Use Cases ### Welcome Email ```java Java theme={null} public class WelcomeEmailService { private EmailApi emailApi; private String apiKey; public WelcomeEmailService(String apiKey) { this.apiKey = apiKey; ApiClient client = Configuration.getDefaultApiClient(); client.setBasePath("https://api.sendpost.io/api/v1"); this.emailApi = new EmailApi(client); } public void sendWelcomeEmail(String userEmail, String firstName) { EmailMessage emailMessage = new EmailMessage(); emailMessage.setSubject("Welcome {{firstName}}!"); From from = new From(); from.setEmail("hello@playwithsendpost.io"); from.setName("SendPost"); emailMessage.setFrom(from); To to = new To(); to.setEmail(userEmail); to.setName(firstName); // Add custom fields for personalization Map customFields = new HashMap<>(); customFields.put("firstName", firstName); to.setCustomFields(customFields); emailMessage.setTo(Arrays.asList(to)); emailMessage.setHtmlBody( "

    Welcome, {{firstName}}!

    " + "

    Thank you for joining us. We're excited to have you on board.

    " + "

    Unsubscribe

    " ); emailMessage.setTextBody( "Welcome, {{firstName}}!\n\n" + "Thank you for joining us. We're excited to have you on board.\n\n" + "Unsubscribe: {{unsubscribe}}" ); emailMessage.setGroups(Arrays.asList("welcome")); emailMessage.setTrackOpens(true); emailMessage.setTrackClicks(true); try { List result = emailApi.sendEmail(apiKey, emailMessage); System.out.println("Welcome email sent: " + result.get(0).getMessageId()); } catch (ApiException e) { System.err.println("Error sending welcome email: " + e.getMessage()); } } } ``` ### Password Reset Email ```java Java theme={null} public class PasswordResetService { private EmailApi emailApi; private String apiKey; public void sendPasswordResetEmail(String userEmail, String resetToken, String firstName) { String resetUrl = "https://yourapp.com/reset-password?token=" + resetToken; EmailMessage emailMessage = new EmailMessage(); emailMessage.setSubject("Reset Your Password"); From from = new From(); from.setEmail("hello@playwithsendpost.io"); from.setName("SendPost"); emailMessage.setFrom(from); To to = new To(); to.setEmail(userEmail); to.setName(firstName); Map customFields = new HashMap<>(); customFields.put("firstName", firstName); customFields.put("resetUrl", resetUrl); to.setCustomFields(customFields); emailMessage.setTo(Arrays.asList(to)); emailMessage.setHtmlBody( "

    Hello {{firstName}},

    " + "

    We received a request to reset your password. Click the button below:

    " + "

    Reset Password

    " + "

    Or copy and paste this link: {{resetUrl}}

    " + "

    This link will expire in 1 hour.

    " ); emailMessage.setGroups(Arrays.asList("password-reset")); emailMessage.setTrackClicks(true); try { emailApi.sendEmail(apiKey, emailMessage); } catch (ApiException e) { System.err.println("Error sending password reset email: " + e.getMessage()); } } } ``` ## 4. Spring Boot Integration ### Create Email Service ```java Java theme={null} package com.example.service; import io.sendpost.client.ApiClient; import io.sendpost.client.ApiException; import io.sendpost.client.Configuration; import io.sendpost.client.api.EmailApi; import io.sendpost.client.model.*; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @Service public class EmailService { private final EmailApi emailApi; private final String apiKey; public EmailService(@Value("${sendpost.api.key}") String apiKey) { this.apiKey = apiKey; ApiClient client = Configuration.getDefaultApiClient(); client.setBasePath("https://api.sendpost.io/api/v1"); this.emailApi = new EmailApi(client); } public void sendEmail(String to, String subject, String htmlBody, String textBody) { EmailMessage emailMessage = new EmailMessage(); emailMessage.setSubject(subject); emailMessage.setHtmlBody(htmlBody); emailMessage.setTextBody(textBody); From from = new From(); from.setEmail("hello@playwithsendpost.io"); from.setName("SendPost"); emailMessage.setFrom(from); To recipient = new To(); recipient.setEmail(to); emailMessage.setTo(Arrays.asList(recipient)); try { emailApi.sendEmail(apiKey, emailMessage); } catch (ApiException e) { throw new RuntimeException("Failed to send email", e); } } } ``` ### Add Configuration Add to `application.properties`: ```properties theme={null} sendpost.api.key=${SENDPOST_API_KEY} ``` Or `application.yml`: ```yaml theme={null} sendpost: api: key: ${SENDPOST_API_KEY} ``` ### Use in Controller ```java Java theme={null} @RestController @RequestMapping("/api/email") public class EmailController { private final EmailService emailService; public EmailController(EmailService emailService) { this.emailService = emailService; } @PostMapping("/send") public ResponseEntity sendEmail(@RequestBody EmailRequest request) { try { emailService.sendEmail( request.getTo(), request.getSubject(), request.getHtmlBody(), request.getTextBody() ); return ResponseEntity.ok().body(Map.of("success", true)); } catch (Exception e) { return ResponseEntity.status(500) .body(Map.of("success", false, "error", e.getMessage())); } } } ``` > [!WARNING] > > Make sure your sender email domain is verified in your SendPost account before > sending emails. ## 5. Next Steps Explore more examples and use cases: > [card] [Java SDK](https://github.com/sendpost/sendpost-java-sdk) > > View the official SDK on GitHub > [card] [SDK Examples](https://github.com/sendpost/sendpost-examples-java) > > Comprehensive email sending examples > [card] [ESP Workflow Example](https://github.com/sendpost/java-esp-example) > > Full-featured example app with comprehensive ESP workflow # JavaScript SDK Quickstart Source: https://docs.sendpost.io/quickstart/javascript-sdk Learn how to configure and send your first email with SendPost JavaScript SDK ## Prerequisites To get the most out of this guide, you'll need to: * [**Create a SendPost Account**](https://app.sendpost.io/register) * [**Install Node.js**](https://nodejs.org/en/download) (v14 or higher) * A **Sub-Account API Key** from your SendPost dashboard > [!NOTE] > > You can find your API keys in your [SendPost > Dashboard](https://app.sendpost.io). Make sure to use your Sub-Account API Key > for sending emails. ## 1. Install Install the SendPost JavaScript SDK using npm: ```shellscript npm theme={null} npm install sendpost-js-sdk --save ``` ## 2. Getting Started Here's a simple example to send your first email: ```javascript JavaScript theme={null} const sendpost = require("sendpost-js-sdk"); const emailApi = new sendpost.EmailApi(); const apiKey = "your_sub_account_api_key"; // Replace with your Sub-Account API Key // Create email message const emailMessage = new sendpost.EmailMessage(); emailMessage.from = { email: "hello@playwithsendpost.io" }; emailMessage.to = [{ email: "gavin@hooli.com" }]; emailMessage.subject = "Hello World"; emailMessage.htmlBody = "it works!"; // Send email const opts = { emailMessage: emailMessage, }; emailApi .sendEmail(apiKey, opts) .then((data) => { console.log("API called successfully. Returned data: ", data); }) .catch((error) => { console.error("Error: ", error); }); ``` > [!WARNING] > > Make sure your sender email domain is verified in your SendPost account before > sending emails. ## 3. Next Steps Explore more examples and use cases: > [card] [JavaScript SDK](https://www.npmjs.com/package/sendpost-js-sdk) > > View the official SDK package on npm > [card] [SDK Examples](https://github.com/sendpost/sendpost-examples-js) > > Comprehensive email sending examples including CC, BCC, and attachments > [card] [ESP Workflow Example](https://github.com/sendpost/js-esp-example) > > Full-featured example app with comprehensive ESP workflow # Laravel Quickstart Source: https://docs.sendpost.io/quickstart/laravel Learn how to send emails with SendPost in your Laravel application using Mailables, Notifications, and custom mail drivers ## Prerequisites To get the most out of this guide, you'll need to: * [**Create a SendPost Account**](https://app.sendpost.io/register) * [**Laravel 9+**](https://laravel.com/docs) * [**PHP 8.1+**](https://www.php.net/downloads.php) * A **Sub-Account API Key** from your SendPost dashboard > [!NOTE] > > You can find your API keys in your [SendPost Dashboard](https://app.sendpost.io). Make sure to use your Sub-Account API Key for sending emails. ## 1. Install Dependencies ```shellscript composer theme={null} composer require sendpost/sendpost-php-sdk -W ``` > [!NOTE] > > The SDK uses Guzzle 7. New Laravel 13 apps ship with Guzzle 8, and `-W` lets Composer switch them to Guzzle 7, which Laravel also supports. ## 2. Environment Setup Add to your `.env` file: ```env theme={null} SENDPOST_API_KEY=your_sub_account_api_key SENDPOST_FROM_EMAIL=hello@playwithsendpost.io SENDPOST_FROM_NAME="SendPost" MAIL_MAILER=sendpost MAIL_FROM_ADDRESS=hello@playwithsendpost.io MAIL_FROM_NAME="SendPost" ``` > [!NOTE] > > Laravel uses `MAIL_FROM_ADDRESS` and `MAIL_FROM_NAME` as the default sender for every mailable and notification. ## 3. Create SendPost Mail Driver Laravel 9+ sends mail through Symfony Mailer, so the driver is a Symfony transport. Create `app/Mail/Drivers/SendPostTransport.php`: ```php PHP theme={null} setApiKey('X-SubAccount-ApiKey', $apiKey); $this->emailApi = new EmailApi(null, $config); } protected function doSend(SentMessage $message): void { $email = MessageConverter::toEmail($message->getOriginalMessage()); $address = fn (Address $a) => array_filter(['email' => $a->getAddress(), 'name' => $a->getName()]); // SendPost sends one email per `to` entry, so CC/BCC go on the first one $to = array_map($address, $email->getTo()); if ($cc = $email->getCc()) { $to[0]['cc'] = array_map($address, $cc); } if ($bcc = $email->getBcc()) { $to[0]['bcc'] = array_map($address, $bcc); } $emailMessage = new EmailMessageObject(); $emailMessage->setFrom($address($email->getFrom()[0])); $emailMessage->setTo($to); $emailMessage->setSubject($email->getSubject()); if ($html = $email->getHtmlBody()) { $emailMessage->setHtmlBody($html); } if ($text = $email->getTextBody()) { $emailMessage->setTextBody($text); } if ($replyTo = $email->getReplyTo()) { $emailMessage->setReplyTo($address($replyTo[0])); } if ($attachments = $email->getAttachments()) { $emailMessage->setAttachments(array_map(fn ($part) => [ 'filename' => $part->getFilename(), 'content' => base64_encode($part->getBody()), ], $attachments)); } try { $responses = $this->emailApi->sendEmail($emailMessage); } catch (ApiException $e) { throw new TransportException($e->getMessage(), $e->getCode(), $e); } $message->setMessageId($responses[0]->getMessageId()); } public function __toString(): string { return 'sendpost'; } } ``` ## 4. Register Mail Driver Add to `app/Providers/AppServiceProvider.php`: ```php PHP theme={null} [ 'api_key' => env('SENDPOST_API_KEY'), 'from' => [ 'email' => env('SENDPOST_FROM_EMAIL'), 'name' => env('SENDPOST_FROM_NAME'), ], ], ``` Update `config/mail.php`: ```php PHP theme={null} 'mailers' => [ // ... other mailers ... 'sendpost' => [ 'transport' => 'sendpost', ], ], ``` ## 5. Send Your First Email ### Using Mail Facade ```php PHP theme={null} use Illuminate\Support\Facades\Mail; Mail::raw('Hello, this is a test email!', function ($message) { $message->to('user@example.com') ->subject('Test Email'); }); ``` ### Using Mailable Class Create a mailable: ```bash theme={null} php artisan make:mail WelcomeEmail ``` Update `app/Mail/WelcomeEmail.php`: ```php PHP theme={null} user = $user; } public function build() { return $this->subject("Welcome {$this->user->first_name}!") ->view('emails.welcome') ->with([ 'firstName' => $this->user->first_name, ]); } } ``` Create `resources/views/emails/welcome.blade.php`: ```blade Blade theme={null} Welcome

    Welcome, {{ $firstName }}!

    Thank you for joining us. We're excited to have you on board.

    Get started by exploring our features:

    • Feature 1
    • Feature 2
    • Feature 3

    If you have any questions, just reply to this email.

    Unsubscribe

    ``` > [!TIP] > > `{{unsubscribe}}` is a SendPost merge tag: SendPost replaces it with a unique [unsubscribe link](/api-reference/common-use-cases/adding-unsubscribe-links) for each recipient. The `@` stops Blade from treating it as a PHP expression. Send the email: ```php PHP theme={null} use App\Mail\WelcomeEmail; use Illuminate\Support\Facades\Mail; Mail::to($user->email)->send(new WelcomeEmail($user)); ``` ## 6. Common Use Cases ### Password Reset Email Create `app/Mail/PasswordResetEmail.php`: ```php PHP theme={null} user = $user; $this->resetUrl = url("/reset-password?token={$token}"); } public function build() { return $this->subject('Reset Your Password') ->view('emails.password-reset') ->with([ 'firstName' => $this->user->first_name, 'resetUrl' => $this->resetUrl, ]); } } ``` Create `resources/views/emails/password-reset.blade.php`: ```blade Blade theme={null} Reset Your Password

    Hello {{ $firstName }},

    We received a request to reset your password. Click the button below:

    Reset Password

    Or copy and paste this link: {{ $resetUrl }}

    This link will expire in 1 hour.

    If you didn't request this, please ignore this email.

    ``` ### Order Confirmation Email Create `app/Mail/OrderConfirmation.php`: ```php PHP theme={null} order = $order; $this->user = $user; } public function build() { return $this->subject("Order {$this->order->id} Confirmed") ->view('emails.order-confirmation') ->with([ 'order' => $this->order, 'user' => $this->user, ]); } } ``` ## 7. Using Notifications Create a notification: ```bash theme={null} php artisan make:notification WelcomeNotification ``` Update `app/Notifications/WelcomeNotification.php`: ```php PHP theme={null} subject("Welcome {$notifiable->first_name}!") ->view('emails.welcome', [ 'firstName' => $notifiable->first_name, ]); } } ``` Send notification: ```php PHP theme={null} $user->notify(new WelcomeNotification()); ``` ## 8. Personalization with Custom Fields Create a custom mailable with personalization: ```php PHP theme={null} recipient = $recipient; $this->customFields = $customFields; } public function build() { // For SendPost personalization, you'll need to use the API directly // or extend the transport to handle customFields return $this->subject('Personalized Email') ->view('emails.personalized') ->with($this->customFields); } } ``` ## 9. Direct API Usage (Alternative) Create `app/Services/SendPostService.php`: ```php PHP theme={null} apiKey = config('services.sendpost.api_key'); $this->fromEmail = config('services.sendpost.from.email'); $this->fromName = config('services.sendpost.from.name'); } public function sendEmail($to, $subject, $htmlBody, $textBody = null, $customFields = []) { $config = Configuration::getDefaultConfiguration(); $config->setApiKey('X-SubAccount-ApiKey', $this->apiKey); $config->setHost('https://api.sendpost.io/api/v1'); $emailApi = new EmailApi(null, $config); $emailMessage = new EmailMessageObject(); $emailMessage->setFrom([ 'email' => $this->fromEmail, 'name' => $this->fromName ]); $recipients = []; if (is_string($to)) { $recipients[] = [ 'email' => $to, 'customFields' => $customFields ]; } else { foreach ($to as $email => $name) { $recipients[] = [ 'email' => $email, 'name' => $name, 'customFields' => $customFields ]; } } $emailMessage->setTo($recipients); $emailMessage->setSubject($subject); $emailMessage->setHtmlBody($htmlBody); if ($textBody) { $emailMessage->setTextBody($textBody); } try { $responses = $emailApi->sendEmail($emailMessage); // one EmailResponse per recipient return ['success' => true, 'message_ids' => array_map(fn ($r) => $r->getMessageId(), $responses)]; } catch (\Exception $e) { return ['success' => false, 'error' => $e->getMessage()]; } } } ``` Use the service: ```php PHP theme={null} use App\Services\SendPostService; $sendPostService = new SendPostService(); $result = $sendPostService->sendEmail( 'user@example.com', 'Welcome {{firstName}}!', '

    Welcome, {{firstName}}!

    ', 'Welcome, {{firstName}}!', ['firstName' => 'John'] ); ``` > [!WARNING] > > Make sure your sender email domain is verified in your SendPost account before sending emails. ## 10. Next Steps Explore more examples and use cases: > [card] [Laravel Documentation](https://laravel.com/docs) > > Learn more about Laravel framework > [card] [SendPost PHP SDK](https://github.com/sendpost/sendpost-php-sdk) > > View the official SDK on GitHub > [card] [Quickstart Example](https://github.com/sendpost/sendpost-laravel-example) > > View a complete working example on GitHub # NestJS Quickstart Source: https://docs.sendpost.io/quickstart/nestjs Learn how to send emails with SendPost in your NestJS application using modules, services, and dependency injection ## Prerequisites To get the most out of this guide, you'll need to: * [**Create a SendPost Account**](https://app.sendpost.io/register) * [**NestJS 9+**](https://nestjs.com/) * [**Node.js 16+**](https://nodejs.org/) * A **Sub-Account API Key** from your SendPost dashboard > [!NOTE] > > You can find your API keys in your [SendPost Dashboard](https://app.sendpost.io). Make sure to use your Sub-Account API Key for sending emails. ## 1. Install Dependencies ```shellscript npm theme={null} npm install sendpost-js-sdk npm install --save-dev @types/node ``` ## 2. Create Email Module Create `src/email/email.module.ts`: ```typescript TypeScript theme={null} import { Module } from '@nestjs/common'; import { EmailService } from './email.service'; @Module({ providers: [EmailService], exports: [EmailService], }) export class EmailModule {} ``` ## 3. Create Email Service Create `src/email/email.service.ts`: ```typescript TypeScript theme={null} import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import sendpost from 'sendpost-js-sdk'; const emailApi = new sendpost.EmailApi(); @Injectable() export class EmailService { private readonly apiKey: string; private readonly fromEmail: string; private readonly fromName: string; constructor(private configService: ConfigService) { this.apiKey = this.configService.get('SENDPOST_API_KEY') || ''; this.fromEmail = this.configService.get('SENDPOST_FROM_EMAIL') || 'hello@playwithsendpost.io'; this.fromName = this.configService.get('SENDPOST_FROM_NAME') || 'SendPost'; } async sendEmail({ to, subject, htmlBody, textBody, from, groups, trackOpens = true, trackClicks = true, customFields, }: { to: string | Array<{ email: string; name?: string; customFields?: Record }>; subject: string; htmlBody: string; textBody?: string; from?: { email: string; name?: string }; groups?: string[]; trackOpens?: boolean; trackClicks?: boolean; customFields?: Record; }) { try { const emailMessage = new sendpost.EmailMessage(); emailMessage.from = from || { email: this.fromEmail, name: this.fromName, }; // Handle single email or array of recipients if (typeof to === 'string') { emailMessage.to = [{ email: to }]; } else { emailMessage.to = to.map(recipient => { if (typeof recipient === 'string') { return { email: recipient }; } return { email: recipient.email, name: recipient.name, customFields: recipient.customFields || customFields, }; }); } emailMessage.subject = subject; emailMessage.htmlBody = htmlBody; emailMessage.textBody = textBody || htmlBody.replace(/<[^>]*>/g, ''); emailMessage.trackOpens = trackOpens; emailMessage.trackClicks = trackClicks; if (groups) { emailMessage.groups = groups; } const response = await emailApi.sendEmail(this.apiKey, { emailMessage }); return { success: true, messageId: response.messageId, data: response, }; } catch (error: any) { console.error('SendPost error:', error); return { success: false, error: error.message || 'Failed to send email', details: error, }; } } } ``` ## 4. Configure Environment Variables Create `.env`: ```env theme={null} SENDPOST_API_KEY=your_sub_account_api_key SENDPOST_FROM_EMAIL=hello@playwithsendpost.io SENDPOST_FROM_NAME=SendPost ``` Update `app.module.ts`: ```typescript TypeScript theme={null} import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { EmailModule } from './email/email.module'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, }), EmailModule, ], }) export class AppModule {} ``` ## 5. Create Email Controller Create `src/email/email.controller.ts`: ```typescript TypeScript theme={null} import { Controller, Post, Body, HttpCode, HttpStatus } from '@nestjs/common'; import { EmailService } from './email.service'; @Controller('email') export class EmailController { constructor(private readonly emailService: EmailService) {} @Post('send') @HttpCode(HttpStatus.OK) async sendEmail(@Body() body: { to: string; subject: string; htmlBody: string; textBody?: string; }) { const result = await this.emailService.sendEmail({ to: body.to, subject: body.subject, htmlBody: body.htmlBody, textBody: body.textBody, }); if (!result.success) { throw new Error(result.error); } return { success: true, messageId: result.messageId, }; } } ``` ## 6. Common Use Cases ### Welcome Email Service Method Add to `email.service.ts`: ```typescript TypeScript theme={null} async sendWelcomeEmail(email: string, firstName: string) { return this.sendEmail({ to: { email, name: firstName, customFields: { firstName }, }, subject: 'Welcome {{firstName}}!', htmlBody: `

    Welcome, {{firstName}}!

    Thank you for joining us. We're excited to have you on board.

    Get started by exploring our features:

    • Feature 1
    • Feature 2
    • Feature 3

    If you have any questions, just reply to this email.

    Unsubscribe

    `, textBody: ` Welcome, {{firstName}}! Thank you for joining us. We're excited to have you on board. Get started by exploring our features: - Feature 1 - Feature 2 - Feature 3 If you have any questions, just reply to this email. Unsubscribe: {{unsubscribe}} `, groups: ['welcome'], }); } ``` ### Password Reset Email ```typescript TypeScript theme={null} async sendPasswordResetEmail(email: string, resetToken: string, firstName: string) { const appUrl = this.configService.get('APP_URL') || 'https://yourapp.com'; const resetUrl = `${appUrl}/reset-password?token=${resetToken}`; return this.sendEmail({ to: { email, name: firstName, customFields: { firstName, resetUrl, }, }, subject: 'Reset Your Password', htmlBody: `

    Hello {{firstName}},

    We received a request to reset your password. Click the button below:

    Reset Password

    Or copy and paste this link: {{resetUrl}}

    This link will expire in 1 hour.

    `, groups: ['password-reset'], trackClicks: true, }); } ``` ## 7. Using in Other Services ```typescript TypeScript theme={null} import { Injectable } from '@nestjs/common'; import { EmailService } from '../email/email.service'; @Injectable() export class UserService { constructor(private readonly emailService: EmailService) {} async createUser(userData: CreateUserDto) { // Create user logic const user = await this.userRepository.create(userData); // Send welcome email await this.emailService.sendWelcomeEmail(user.email, user.firstName); return user; } } ``` ## 8. Using with Queues (Bull) Install Bull: ```bash theme={null} npm install @nestjs/bull bull ``` Create email queue: ```typescript TypeScript theme={null} import { Module } from '@nestjs/common'; import { BullModule } from '@nestjs/bull'; import { EmailProcessor } from './email.processor'; @Module({ imports: [ BullModule.registerQueue({ name: 'email', }), ], providers: [EmailProcessor], }) export class EmailQueueModule {} ``` Create processor: ```typescript TypeScript theme={null} import { Processor, Process } from '@nestjs/bull'; import { Job } from 'bull'; import { EmailService } from '../email.service'; @Processor('email') export class EmailProcessor { constructor(private readonly emailService: EmailService) {} @Process('welcome') async handleWelcomeEmail(job: Job) { const { email, firstName } = job.data; return this.emailService.sendWelcomeEmail(email, firstName); } } ``` > [!WARNING] > > Make sure your sender email domain is verified in your SendPost account before sending emails. ## 9. Next Steps Explore more examples and use cases: > [card] [NestJS Documentation](https://docs.nestjs.com/) > > Learn more about NestJS framework > [card] [SendPost JavaScript SDK](https://www.npmjs.com/package/sendpost-js-sdk) > > View the official SDK package on npm > [card] [Quickstart Example](https://github.com/sendpost/sendpost-nestjs-example) > > View a complete working example on GitHub # Netlify Functions Quickstart Source: https://docs.sendpost.io/quickstart/netlify-functions Learn how to send emails with SendPost in Netlify Serverless Functions using JavaScript and TypeScript ## Prerequisites To get the most out of this guide, you'll need to: * [**Create a SendPost Account**](https://app.sendpost.io/register) * [**Netlify Account**](https://www.netlify.com/) (free tier works) * A **Sub-Account API Key** from your SendPost dashboard > [!NOTE] > > You can find your API keys in your [SendPost Dashboard](https://app.sendpost.io). Make sure to use your Sub-Account API Key for sending emails. ## 1. Install Dependencies ```shellscript npm theme={null} npm install sendpost-js-sdk ``` ## 2. Project Structure Create a Netlify function: ``` netlify/ functions/ send-email.js ``` Or if using TypeScript: ``` netlify/ functions/ send-email.ts ``` ## 3. Basic Email Function Create `netlify/functions/send-email.js`: ```javascript JavaScript theme={null} const sendpost = require('sendpost-js-sdk'); const emailApi = new sendpost.EmailApi(); exports.handler = async (event, context) => { // Handle CORS const headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Allow-Methods': 'POST, OPTIONS', }; if (event.httpMethod === 'OPTIONS') { return { statusCode: 200, headers, body: '', }; } if (event.httpMethod !== 'POST') { return { statusCode: 405, headers, body: JSON.stringify({ error: 'Method not allowed' }), }; } try { const { to, subject, htmlBody, textBody } = JSON.parse(event.body); if (!to || !subject || !htmlBody) { return { statusCode: 400, headers, body: JSON.stringify({ success: false, error: 'Missing required fields: to, subject, htmlBody', }), }; } const emailMessage = new sendpost.EmailMessage(); emailMessage.from = { email: 'hello@playwithsendpost.io', name: 'SendPost', }; emailMessage.to = [{ email: to }]; emailMessage.subject = subject; emailMessage.htmlBody = htmlBody; emailMessage.textBody = textBody || htmlBody.replace(/<[^>]*>/g, ''); emailMessage.trackOpens = true; emailMessage.trackClicks = true; const response = await emailApi.sendEmail( process.env.SENDPOST_API_KEY, { emailMessage } ); return { statusCode: 200, headers: { ...headers, 'Content-Type': 'application/json', }, body: JSON.stringify({ success: true, messageId: response.messageId, }), }; } catch (error) { console.error('SendPost error:', error); return { statusCode: 500, headers: { ...headers, 'Content-Type': 'application/json', }, body: JSON.stringify({ success: false, error: error.message, }), }; } }; ``` ### TypeScript Version Create `netlify/functions/send-email.ts`: ```typescript TypeScript theme={null} import { Handler } from '@netlify/functions'; import sendpost from 'sendpost-js-sdk'; const emailApi = new sendpost.EmailApi(); export const handler: Handler = async (event, context) => { const headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Allow-Methods': 'POST, OPTIONS', }; if (event.httpMethod === 'OPTIONS') { return { statusCode: 200, headers, body: '', }; } if (event.httpMethod !== 'POST') { return { statusCode: 405, headers, body: JSON.stringify({ error: 'Method not allowed' }), }; } try { const { to, subject, htmlBody, textBody } = JSON.parse(event.body); if (!to || !subject || !htmlBody) { return { statusCode: 400, headers, body: JSON.stringify({ success: false, error: 'Missing required fields: to, subject, htmlBody', }), }; } const emailMessage = new sendpost.EmailMessage(); emailMessage.from = { email: 'hello@playwithsendpost.io', name: 'SendPost', }; emailMessage.to = [{ email: to }]; emailMessage.subject = subject; emailMessage.htmlBody = htmlBody; emailMessage.textBody = textBody || htmlBody.replace(/<[^>]*>/g, ''); emailMessage.trackOpens = true; emailMessage.trackClicks = true; const response = await emailApi.sendEmail( process.env.SENDPOST_API_KEY!, { emailMessage } ); return { statusCode: 200, headers: { ...headers, 'Content-Type': 'application/json', }, body: JSON.stringify({ success: true, messageId: response.messageId, }), }; } catch (error: any) { console.error('SendPost error:', error); return { statusCode: 500, headers: { ...headers, 'Content-Type': 'application/json', }, body: JSON.stringify({ success: false, error: error.message, }), }; } }; ``` ## 4. Environment Variables Create `netlify.toml`: ```toml theme={null} [build] functions = "netlify/functions" [build.environment] SENDPOST_API_KEY = "your_sub_account_api_key" ``` Or set in Netlify Dashboard: 1. Go to Site settings → Environment variables 2. Add `SENDPOST_API_KEY` ## 5. Common Use Cases ### Welcome Email Function Create `netlify/functions/welcome-email.js`: ```javascript JavaScript theme={null} const sendpost = require('sendpost-js-sdk'); const emailApi = new sendpost.EmailApi(); exports.handler = async (event, context) => { const headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Allow-Methods': 'POST, OPTIONS', }; if (event.httpMethod === 'OPTIONS') { return { statusCode: 200, headers, body: '' }; } try { const { email, firstName } = JSON.parse(event.body); const emailMessage = new sendpost.EmailMessage(); emailMessage.from = { email: 'hello@playwithsendpost.io', name: 'SendPost', }; emailMessage.to = [{ email, name: firstName, customFields: { firstName }, }]; emailMessage.subject = 'Welcome {{firstName}}!'; emailMessage.htmlBody = `

    Welcome, {{firstName}}!

    Thank you for joining us. We're excited to have you on board.

    Unsubscribe

    `; emailMessage.groups = ['welcome']; const response = await emailApi.sendEmail( process.env.SENDPOST_API_KEY, { emailMessage } ); return { statusCode: 200, headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify({ success: true, messageId: response.messageId, }), }; } catch (error) { return { statusCode: 500, headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify({ success: false, error: error.message }), }; } }; ``` ## 6. Testing Locally Install Netlify CLI: ```bash theme={null} npm install -g netlify-cli ``` Run locally: ```bash theme={null} netlify dev ``` Test your function: ```bash theme={null} curl -X POST http://localhost:8888/.netlify/functions/send-email \ -H "Content-Type: application/json" \ -d '{ "to": "user@example.com", "subject": "Test Email", "htmlBody": "

    Hello from Netlify!

    " }' ``` ## 7. Deploy Deploy to Netlify: ```bash theme={null} netlify deploy --prod ``` Or connect your Git repository for automatic deployments. > [!WARNING] > > Make sure your sender email domain is verified in your SendPost account before sending emails. ## 8. Next Steps Explore more examples and use cases: > [card] [Netlify Functions](https://docs.netlify.com/functions/overview/) > > Learn more about Netlify Functions > [card] [SendPost JavaScript SDK](https://www.npmjs.com/package/sendpost-js-sdk) > > View the official SDK package on npm > [card] [Quickstart Example](https://github.com/sendpost/sendpost-netlify-functions-example) > > View a complete working example on GitHub # Next.js Quickstart Source: https://docs.sendpost.io/quickstart/nextjs Learn how to send emails with SendPost in your Next.js application using API routes, Server Actions, and React components ## Prerequisites To get the most out of this guide, you'll need to: * [**Create a SendPost Account**](https://app.sendpost.io/register) * [**Next.js 13+**](https://nextjs.org/docs) with App Router or Pages Router * A **Sub-Account API Key** from your SendPost dashboard > [!NOTE] > > You can find your API keys in your [SendPost Dashboard](https://app.sendpost.io). Make sure to use your Sub-Account API Key for sending emails. ## 1. Install Dependencies ```shellscript npm theme={null} npm install sendpost-js-sdk ``` ## 2. Environment Setup Create or update your `.env.local` file: ```env theme={null} SENDPOST_API_KEY=your_sub_account_api_key SENDPOST_FROM_EMAIL=hello@playwithsendpost.io SENDPOST_FROM_NAME=SendPost ``` ## 3. Send Your First Email ### Using API Routes (App Router) Create `app/api/send-email/route.ts`: ```typescript TypeScript theme={null} import { NextRequest, NextResponse } from 'next/server'; import sendpost from 'sendpost-js-sdk'; const emailApi = new sendpost.EmailApi(); export async function POST(request: NextRequest) { try { const { to, subject, htmlBody, textBody } = await request.json(); const emailMessage = new sendpost.EmailMessage(); emailMessage.from = { email: process.env.SENDPOST_FROM_EMAIL!, name: process.env.SENDPOST_FROM_NAME }; emailMessage.to = [{ email: to }]; emailMessage.subject = subject; emailMessage.htmlBody = htmlBody; emailMessage.textBody = textBody; emailMessage.trackOpens = true; emailMessage.trackClicks = true; const opts = { emailMessage: emailMessage, }; const response = await emailApi.sendEmail( process.env.SENDPOST_API_KEY!, opts ); return NextResponse.json({ success: true, messageId: response.messageId }); } catch (error: any) { console.error('SendPost error:', error); return NextResponse.json( { success: false, error: error.message }, { status: 500 } ); } } ``` ### Using Server Actions (App Router) Create `app/actions/sendEmail.ts`: ```typescript TypeScript theme={null} 'use server'; import sendpost from 'sendpost-js-sdk'; const emailApi = new sendpost.EmailApi(); export async function sendEmail({ to, subject, htmlBody, textBody, }: { to: string; subject: string; htmlBody: string; textBody?: string; }) { try { const emailMessage = new sendpost.EmailMessage(); emailMessage.from = { email: process.env.SENDPOST_FROM_EMAIL!, name: process.env.SENDPOST_FROM_NAME, }; emailMessage.to = [{ email: to }]; emailMessage.subject = subject; emailMessage.htmlBody = htmlBody; emailMessage.textBody = textBody || htmlBody.replace(/<[^>]*>/g, ''); emailMessage.trackOpens = true; emailMessage.trackClicks = true; const response = await emailApi.sendEmail( process.env.SENDPOST_API_KEY!, { emailMessage } ); return { success: true, messageId: response.messageId }; } catch (error: any) { console.error('SendPost error:', error); return { success: false, error: error.message }; } } ``` ## 4. Common Use Cases ### Welcome Email Create `app/actions/welcomeEmail.ts`: ```typescript TypeScript theme={null} 'use server'; import sendpost from 'sendpost-js-sdk'; const emailApi = new sendpost.EmailApi(); export async function sendWelcomeEmail({ email, firstName, }: { email: string; firstName: string; }) { const emailMessage = new sendpost.EmailMessage(); emailMessage.from = { email: process.env.SENDPOST_FROM_EMAIL!, name: process.env.SENDPOST_FROM_NAME, }; emailMessage.to = [ { email, name: firstName, customFields: { firstName, }, }, ]; emailMessage.subject = 'Welcome to {{firstName}}!'; emailMessage.htmlBody = `

    Welcome, {{firstName}}!

    Thank you for joining us. We're excited to have you on board.

    Get started by exploring our features:

    • Feature 1
    • Feature 2
    • Feature 3

    If you have any questions, just reply to this email.

    Unsubscribe

    `; emailMessage.textBody = ` Welcome, {{firstName}}! Thank you for joining us. We're excited to have you on board. Get started by exploring our features: - Feature 1 - Feature 2 - Feature 3 If you have any questions, just reply to this email. Unsubscribe: {{unsubscribe}} `; emailMessage.trackOpens = true; emailMessage.trackClicks = true; emailMessage.groups = ['welcome']; try { const response = await emailApi.sendEmail( process.env.SENDPOST_API_KEY!, { emailMessage } ); return { success: true, messageId: response.messageId }; } catch (error: any) { return { success: false, error: error.message }; } } ``` ### Password Reset Email Create `app/actions/passwordReset.ts`: ```typescript TypeScript theme={null} 'use server'; import sendpost from 'sendpost-js-sdk'; const emailApi = new sendpost.EmailApi(); export async function sendPasswordResetEmail({ email, resetToken, firstName, }: { email: string; resetToken: string; firstName: string; }) { const resetUrl = `${process.env.NEXT_PUBLIC_APP_URL}/reset-password?token=${resetToken}`; const emailMessage = new sendpost.EmailMessage(); emailMessage.from = { email: process.env.SENDPOST_FROM_EMAIL!, name: process.env.SENDPOST_FROM_NAME, }; emailMessage.to = [ { email, name: firstName, customFields: { firstName, resetUrl, }, }, ]; emailMessage.subject = 'Reset Your Password'; emailMessage.htmlBody = `

    Hello {{firstName}},

    We received a request to reset your password. Click the button below to create a new password:

    Reset Password

    Or copy and paste this link into your browser:

    {{resetUrl}}

    This link will expire in 1 hour.

    If you didn't request this, please ignore this email.

    `; emailMessage.textBody = ` Hello {{firstName}}, We received a request to reset your password. Click the link below to create a new password: {{resetUrl}} This link will expire in 1 hour. If you didn't request this, please ignore this email. `; emailMessage.trackClicks = true; emailMessage.groups = ['password-reset']; try { const response = await emailApi.sendEmail( process.env.SENDPOST_API_KEY!, { emailMessage } ); return { success: true, messageId: response.messageId }; } catch (error: any) { return { success: false, error: error.message }; } } ``` ### Order Confirmation Email Create `app/actions/orderConfirmation.ts`: ```typescript TypeScript theme={null} 'use server'; import sendpost from 'sendpost-js-sdk'; const emailApi = new sendpost.EmailApi(); interface OrderItem { name: string; price: number; quantity: number; } export async function sendOrderConfirmation({ email, firstName, orderId, items, total, }: { email: string; firstName: string; orderId: string; items: OrderItem[]; total: number; }) { const emailMessage = new sendpost.EmailMessage(); emailMessage.from = { email: process.env.SENDPOST_FROM_EMAIL!, name: process.env.SENDPOST_FROM_NAME, }; emailMessage.to = [ { email, name: firstName, customFields: { firstName, orderId, items, total: total.toFixed(2), }, }, ]; emailMessage.subject = 'Order {{orderId}} Confirmed'; emailMessage.htmlBody = `

    Thank you for your order, {{firstName}}!

    Your order {{orderId}} has been confirmed.

    Order Details

    {{#each items}} {{/each}}
    Item Quantity Price
    {{name}} {{quantity}} ${{price}}
    Total: ${{total}}

    We'll send you a shipping confirmation once your order is on its way.

    Unsubscribe from order updates

    `; emailMessage.trackOpens = true; emailMessage.trackClicks = true; emailMessage.groups = ['order-confirmation']; try { const response = await emailApi.sendEmail( process.env.SENDPOST_API_KEY!, { emailMessage } ); return { success: true, messageId: response.messageId }; } catch (error: any) { return { success: false, error: error.message }; } } ``` ## 5. Using in React Components ### Contact Form Example Create `app/components/ContactForm.tsx`: ```typescript TypeScript theme={null} 'use client'; import { useState } from 'react'; import { sendEmail } from '@/app/actions/sendEmail'; export default function ContactForm() { const [status, setStatus] = useState<'idle' | 'sending' | 'success' | 'error'>('idle'); const [message, setMessage] = useState(''); async function handleSubmit(e: React.FormEvent) { e.preventDefault(); setStatus('sending'); setMessage(''); const formData = new FormData(e.currentTarget); const result = await sendEmail({ to: formData.get('email') as string, subject: `Contact from ${formData.get('name')}`, htmlBody: `

    New Contact Form Submission

    Name: ${formData.get('name')}

    Email: ${formData.get('email')}

    Message:

    ${formData.get('message')}

    `, }); if (result.success) { setStatus('success'); setMessage('Email sent successfully!'); e.currentTarget.reset(); } else { setStatus('error'); setMessage(result.error || 'Failed to send email'); } } return (
    {{ message }}
    ``` ## 7. Runtime Config Add to `nuxt.config.ts`: ```typescript TypeScript theme={null} export default defineNuxtConfig({ runtimeConfig: { sendpostApiKey: process.env.SENDPOST_API_KEY, sendpostFromEmail: process.env.SENDPOST_FROM_EMAIL || 'hello@playwithsendpost.io', sendpostFromName: process.env.SENDPOST_FROM_NAME || 'SendPost', public: { appUrl: process.env.APP_URL || 'https://yourapp.com', }, }, }); ``` > [!WARNING] > > Make sure your sender email domain is verified in your SendPost account before sending emails. ## 8. Next Steps Explore more examples and use cases: > [card] [Nuxt.js Documentation](https://nuxt.com/docs) > > Learn more about Nuxt.js framework > [card] [SendPost JavaScript SDK](https://www.npmjs.com/package/sendpost-js-sdk) > > View the official SDK package on npm > [card] [Personalization Guide](/api-reference/common-use-cases/personalisation-within-emails) > > Learn how to personalize emails with Handlebars templates # PHP SDK Quickstart Source: https://docs.sendpost.io/quickstart/php-sdk Learn how to configure and send your first email with SendPost PHP SDK ## Prerequisites To get the most out of this guide, you'll need to: * [**Create a SendPost Account**](https://app.sendpost.io/register) * [**Install PHP 8.1+**](https://www.php.net/downloads.php) * A **Sub-Account API Key** from your SendPost dashboard > [!NOTE] > > You can find your API keys in your [SendPost > Dashboard](https://app.sendpost.io). Make sure to use your Sub-Account API Key > for sending emails. ## 1. Install ### **Composer** To install the bindings via [Composer](https://getcomposer.org/), use the following command on the command line: ```shellscript shell theme={null} composer require sendpost/sendpost-php-sdk ``` Or, add the following to `composer.json`: ```json composer.json theme={null} "require": { "sendpost/sendpost-php-sdk": "^2.0" } ``` Then run `composer install` ### **Manual Installation** Download the files and include `autoload.php`: ```php theme={null} setApiKey('X-SubAccount-ApiKey', 'your_api_key'); // Sub-Account API Key $apiInstance = new sendpost\api\EmailApi(new GuzzleHttp\Client(), $config); $from = new \sendpost\model\EmailAddress(); $from->setEmail('hello@playwithsendpost.io'); $to = new \sendpost\model\Recipient(); $to->setEmail('gavin@hooli.com'); $email_message = new \sendpost\model\EmailMessageObject(); $email_message->setFrom($from); $email_message->setTo([$to]); $email_message->setSubject('Hello World'); $email_message->setHtmlBody('it works!'); try { $result = $apiInstance->sendEmail($email_message); print_r($result); } catch (Exception $e) { echo 'Exception when calling EmailApi->sendEmail: ', $e->getMessage(), PHP_EOL; } ``` > [!WARNING] > > Make sure your sender email domain is verified in your SendPost account before > sending emails. ## 3. Next Steps Explore more examples and use cases: > [card] [PHP SDK](https://packagist.org/packages/sendpost/sendpost-php-sdk) > > View the official SDK package on Packagist > [card] [SDK Examples](https://github.com/sendpost/sendpost-examples-php) > > Comprehensive email sending examples > [card] [ESP Workflow Example](https://github.com/sendpost/php-esp-example) > > Full-featured example app with comprehensive ESP workflow # Python SDK Quickstart Source: https://docs.sendpost.io/quickstart/python-sdk Learn how to configure and send your first email with SendPost Python SDK ## Prerequisites To get the most out of this guide, you'll need to: * [**Create a SendPost Account**](https://app.sendpost.io/register) * [**Install Python >v3.0**](https://www.python.org/downloads/) * A **Sub-Account API Key** from your SendPost dashboard > [!NOTE] > > You can find your API keys in your [SendPost > Dashboard](https://app.sendpost.io). Make sure to use your Sub-Account API Key > for sending emails. ## 1. Install ```shellscript pip theme={null} pip install sendpost_python_sdk ``` ## 2. Getting Started ```python Python theme={null} import os import sendpost_python_sdk from sendpost_python_sdk.api import EmailApi from sendpost_python_sdk.models import EmailMessageObject, EmailAddress, Recipient configuration = sendpost_python_sdk.Configuration(host="https://api.sendpost.io/api/v1") configuration.api_key['subAccountAuth'] = "your_sub_account_api_key" with sendpost_python_sdk.ApiClient(configuration) as api_client: email_message = EmailMessageObject() email_message.var_from = EmailAddress(email="hello@playwithsendpost.io") email_message.to = [Recipient(email="gavin@hooli.com")] email_message.subject = "Hello World" email_message.html_body = "it works!" try: response = EmailApi(api_client).send_email(email_message)[0] print(f"Email sent! Message ID: {response.message_id}") except sendpost_python_sdk.exceptions.ApiException as e: print(f"Error: {e.status} - {e.body}") ``` > [!WARNING] > > Make sure your sender email domain is verified in your SendPost account before > sending emails. ## 3. Next Steps Explore more examples and use cases: > [card] [Python SDK](https://pypi.org/project/sendpost-python-sdk/) > > View the official SDK package on PyPI > [card] [SDK Examples](https://github.com/sendpost/sendpost-examples-python) > > Comprehensive email sending examples > [card] [ESP Workflow Example](https://github.com/sendpost/python-esp-example) > > Full-featured example app with comprehensive ESP workflow # React Quickstart Source: https://docs.sendpost.io/quickstart/react Learn how to send emails with SendPost in your React application using hooks, forms, and API integration ## Prerequisites To get the most out of this guide, you'll need to: * [**Create a SendPost Account**](https://app.sendpost.io/register) * [**React 18+**](https://react.dev/) * A backend API endpoint (Next.js, Express, etc.) or direct API calls * A **Sub-Account API Key** from your SendPost dashboard > [!NOTE] > > You can find your API keys in your [SendPost Dashboard](https://app.sendpost.io). Make sure to use your Sub-Account API Key for sending emails. > [!WARNING] > > **Security Note:** Never expose your SendPost API key in client-side React code. Always use a backend API endpoint to send emails. The examples below show both approaches, but prefer the backend approach for production. ## 1. Install Dependencies ```shellscript npm theme={null} npm install axios # Optional: if using SendPost SDK directly (not recommended for production) npm install sendpost-js-sdk ``` ## 2. Create Email Service Hook Create `hooks/useEmail.js`: ```javascript JavaScript theme={null} import { useState } from 'react'; import axios from 'axios'; const API_BASE_URL = process.env.REACT_APP_API_URL || 'http://localhost:3000/api'; export function useEmail() { const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [success, setSuccess] = useState(false); const sendEmail = async (emailData) => { setLoading(true); setError(null); setSuccess(false); try { const response = await axios.post(`${API_BASE_URL}/send-email`, emailData); setSuccess(true); return { success: true, data: response.data }; } catch (err) { const errorMessage = err.response?.data?.error || err.message || 'Failed to send email'; setError(errorMessage); return { success: false, error: errorMessage }; } finally { setLoading(false); } }; const sendWelcomeEmail = async ({ email, firstName }) => { return sendEmail({ to: email, subject: 'Welcome!', htmlBody: `

    Welcome, ${firstName}!

    Thank you for joining us.

    Unsubscribe

    `, groups: ['welcome'], }); }; const sendPasswordReset = async ({ email, resetToken, firstName }) => { const resetUrl = `${window.location.origin}/reset-password?token=${resetToken}`; return sendEmail({ to: email, subject: 'Reset Your Password', htmlBody: `

    Hello ${firstName},

    Click the link below to reset your password:

    Reset Password

    This link will expire in 1 hour.

    `, groups: ['password-reset'], }); }; return { sendEmail, sendWelcomeEmail, sendPasswordReset, loading, error, success, }; } ``` ## 3. Contact Form Component Create `components/ContactForm.jsx`: ```javascript JavaScript theme={null} import React, { useState } from 'react'; import { useEmail } from '../hooks/useEmail'; export default function ContactForm() { const { sendEmail, loading, error, success } = useEmail(); const [formData, setFormData] = useState({ name: '', email: '', message: '', }); const handleSubmit = async (e) => { e.preventDefault(); const result = await sendEmail({ to: 'contact@yourdomain.com', subject: `Contact from ${formData.name}`, htmlBody: `

    New Contact Form Submission

    Name: ${formData.name}

    Email: ${formData.email}

    Message:

    ${formData.message.replace(/\n/g, '
    ')}

    `, textBody: ` New Contact Form Submission Name: ${formData.name} Email: ${formData.email} Message: ${formData.message} `, }); if (result.success) { setFormData({ name: '', email: '', message: '' }); } }; const handleChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value, }); }; return (