# Email Flows

Email Flows sends automated emails to your customers when something happens:
they leave a cart, stop ordering, place a first order, or come due for a
product they buy regularly. You draw each flow as a set of steps in the
dashboard. BasketBooster runs it for every customer and sends the emails
through **your own** email provider account, from your own domain.

Requires the **Email Flows** feature on your plan. Dashboard: the
**Automation** section. Every endpoint below takes your secret API key
(`X-API-Key`) or a dashboard session.

## How it fits together

1. **Contacts.** Your store tells BasketBooster who its customers are: email,
   name, language and whether they agreed to marketing email. The WooCommerce
   plugin does this for you; other stores call `PUT /contacts/batch`.
2. **A provider.** You connect Resend or Brevo with your own API key and set
   the address emails come from.
3. **Templates.** You build emails from blocks: heading, text, button, image,
   products, coupon code.
4. **Flows.** You pick a trigger and add steps. Publishing turns the flow on.

Unlike the [Customer Intelligence Feed](customer-feed.md) and
[Webhooks](webhooks.md), where your own tools do the sending, Email Flows
stores your customers' email addresses so that it can send for you. Only
customers marked as subscribed are emailed. See [What we store](#what-we-store).

## Contacts

Contacts are keyed by **your store's customer id**, the same id you send as
`user_id` with events and orders. That shared id is how a flow connects an
abandoned cart to an address.

```bash
curl -X PUT "$API/contacts/batch" -H "X-API-Key: $SK" -H "Content-Type: application/json" -d '{
  "backfill": true,
  "contacts": [
    {"customer_id": "1042", "email": "anna@example.com", "first_name": "Anna",
     "locale": "bg", "consent": "subscribed", "store_created_at": "2025-03-14T09:12:00Z"}
  ]
}'
```

| field | notes |
|---|---|
| `customer_id` | required. Your store's id for the customer |
| `email` | required |
| `first_name`, `last_name`, `locale` | optional. `locale` picks the language of the unsubscribe page and link |
| `consent` | `subscribed`, `unsubscribed` or `unknown` (default). Only `subscribed` contacts are emailed |
| `store_created_at` | when the customer signed up. Used by the new customer trigger |

Up to 500 contacts per call. The response counts `created`, `updated` and
`rejected` rows (with a reason for each rejected one) and how many customers
were `enrolled` in a welcome flow.

Set `"backfill": true` when you import customers who already exist. Without
it, every customer who signed up in the last 24 hours and is new to
BasketBooster starts your new customer flow.

Other endpoints:

- `PUT /contacts/{customer_id}` creates or updates one contact.
- `DELETE /contacts/{customer_id}` erases a contact and takes it out of every
  flow. Call it when a customer account is deleted or asks to be erased.
- `GET /contacts` lists contacts with masked addresses and a count per
  consent value.
- `GET /contacts/unsubscribes?since=` lists customers who unsubscribed
  through an email, bounced or complained. Poll it and switch marketing off
  for them in your store. Pass the `next_since` value from the last answer.

### Consent and suppression

An unsubscribe, a hard bounce or a spam complaint puts the address on a
suppression list. After that the address is never emailed, even if your
store keeps sending `"consent": "subscribed"` for it. In the dashboard you
can lift an unsubscribe by hand. Bounces and complaints stay, because
mailing them again damages your sender reputation.

## Connecting your provider

Dashboard: **Automation → Sending**. API: `GET` / `PUT` / `DELETE
/email/provider` and `POST /email/provider/test`.

| provider | key | delivery updates |
|---|---|---|
| Resend | an API key with sending access | signed. Paste the webhook's signing secret |
| Brevo | a v3 API key | not signed. The webhook address itself is the secret |

Your key is checked with the provider when you save it and stored encrypted.
After that the API only returns its last four characters.

Set the sender name and address, then switch sending on. The address has to
belong to a domain you have verified with the provider. If the provider says
it is not verified, sending stays off.

To hear about bounces, complaints, opens and clicks, add the **webhook
address** shown on that page as a webhook in your provider account. For
Resend, also paste the signing secret it gives you. Without the webhook,
emails still go out, but bounced addresses are not suppressed for you.

## Templates

Dashboard: **Automation → Email templates**. API: `/email/templates`
(`GET`, `POST`, `GET/PUT/DELETE /{id}`), plus `POST /email/templates/preview`
and `POST /email/templates/{id}/test-send`.

A template is a subject, an optional preview text and a list of blocks:

| block | what it shows |
|---|---|
| `heading`, `text` | your copy. Text supports `**bold**`, `*italic*` and `[links](https://...)` |
| `button` | a link button |
| `image` | an image by URL, optionally linked |
| `product_grid` | 1 to 6 products from a source, see below |
| `coupon` | a discount code: one you created in your store, or a new one for each customer (see [Discount codes](#discount-codes)) |
| `spacer` | vertical space |
| `footer` | your footer text and the unsubscribe link |

Every email ends with an unsubscribe link. If a template has no footer, one
is added.

Product sources: `recommended` (the customer's own recommendations),
`cart` (what they left in the cart), `viewed` (what they looked at),
`replenishment` (products they are due to restock) and `trending` (your best
sellers). Out-of-stock products are left out. Recommended and viewed grids
are topped up with best sellers, so they always fill.

Variables you can use in the subject and in any text:
`{{first_name}}`, `{{last_name}}`, `{{store_name}}`. Add a fallback for
customers without a name: `{{first_name|default:"there"}}`.

The preview and the test send use sample data and your real best sellers. A
test send only goes to the address of someone with a login on your
BasketBooster account.

## Discount codes

A coupon block works in one of two ways.

**One code for everyone.** You create a coupon in your store and type its
code into the block. Every recipient sees the same code. Nothing else is
needed.

**A separate code for each customer.** You set the rules in the block and
BasketBooster creates a new code every time the email is sent:

| setting | meaning |
|---|---|
| `discount_type` | `percent` (off the order) or `fixed` (an amount in your store currency) |
| `amount` | 1 to 100 for a percentage, or the amount |
| `usage_limit` | how many orders the code works for. 1 = once, 0 = no limit |
| `expires_days` | days until the code stops working (1 to 365, default 14) |
| `prefix` | what the code starts with, for example `SAVE` gives `SAVE-7K3MQ9XD` |

Your store is what takes money off an order, so it has to know these codes.
With the WooCommerce or OpenCart plugin this needs no setup: the first time
a shopper enters one of the codes, the plugin checks it with BasketBooster
and creates a normal store coupon with the same rules, limited to that
customer. You manage it in your store like any other coupon. A flow that
uses unique codes cannot be published until your store has a plugin version
that supports them (WooCommerce 0.6.0, OpenCart 0.3.0) or your own
integration has called `/coupons`.

### Coupons API

For your own integration. All calls use the secret `X-API-Key`.

| call | what it does |
|---|---|
| `GET /coupons/{code}` | Look up a code. `404` means it is not one of ours. Apply it only when `status` is `active` |
| `POST /coupons/{code}/redeem` | Report an order that used the code: `{"order_id": "1001"}`. The same order is counted once |
| `GET /coupons?since=...&unconfirmed=true&limit=200` | Codes created or changed after `since` (ISO 8601), oldest first |
| `POST /coupons/ack` | Confirm your store created these codes: `{"codes": ["SAVE-7K3MQ9XD"]}` |

A code looks like this:

```json
{
  "code": "SAVE-7K3MQ9XD",
  "status": "active",
  "customer_id": "42",
  "discount_type": "percent",
  "amount": 10.0,
  "currency": null,
  "usage_limit": 1,
  "times_used": 0,
  "expires_at": "2026-11-28T10:00:00+00:00",
  "confirmed": false
}
```

`status` is `active`, `used` (the limit is reached), `expired` or
`cancelled` (the contact was erased). `currency` is set for `fixed`
discounts.

There are two ways to keep your store in step. Pick one with
`PUT /email/settings` and `{"coupon_sync": "lookup"}` or `"confirm"`:

- `lookup` (the default). When a shopper enters a code your store does not
  know, call `GET /coupons/{code}` and apply the rules. Nothing is created
  ahead of time. Use this when you can run code at the moment a coupon is
  entered.
- `confirm`. Use this when the store must know a code before the shopper
  arrives. Poll `GET /coupons?unconfirmed=true`, create each code in the
  store, then call `POST /coupons/ack`. Each email waits until its code is
  confirmed. If that takes more than 30 minutes the email is not sent, so a
  customer never receives a code that does not work.

In both cases call `POST /coupons/{code}/redeem` after an order uses a code.
That is what keeps `usage_limit` correct and what the dashboard counts.

The dashboard lists every issued code under Discount codes: the flow that
sent it, the customer, the discount, how many times it was used and whether
it is still valid. The same list is available from `GET /email/coupons`
(newest first, with an optional `status` of `active`, `used`, `expired` or
`cancelled`).

## Flows

Dashboard: **Automation → Flows**. A flow is one trigger followed by steps.

Every account starts with one ready-made flow for each trigger below, with its
own email template in the account's language. They are drafts, so they send
nothing until you open one, adjust the text and publish it. You can delete the
ones you do not need; they are not created again.

The ones that ask a customer to come back or finish an order (welcome,
abandoned cart, late usual order, at risk, drifting away, best customers)
include a coupon block with the code left empty. Create the discount in your
store and type its code into the block, or switch the block to a separate
code for each customer, then publish. A flow cannot be published
while an email it sends has an empty coupon code or another unfinished block,
so remove the coupon block if you would rather send no offer.

### Triggers

| trigger | starts when | timing |
|---|---|---|
| `new_customer` | a contact is synced for the first time | within a minute |
| `order_placed` | a known customer places an order | about 5 to 8 minutes |
| `cart_abandoned` | a known customer adds to cart, then goes idle | idle time you choose (30 minutes or more) |
| `browse_abandoned` | a known customer views products, adds nothing, then goes idle | idle time you choose |
| `became_at_risk`, `predicted_order_missed`, `replenishment_due`, `segment_changed`, `churn_threshold_crossed`, `reactivated`, `new_champion` | the nightly customer refresh detects the change | once a day. Needs Customer Intelligence |

"Known customer" means a logged-in customer with a synced contact. Guest
checkouts and anonymous visitors have no address on file and never enter a
flow.

A trigger can carry filters ("only if total spent is at least 200"), using
the same rules as a condition step.

### Steps

| step | does |
|---|---|
| Wait | pauses the customer for 5 minutes up to 90 days |
| Condition | sends the customer down a yes or a no branch |
| Send email | sends a template |
| Call webhook | posts a signed `flow.action` event to one of your [webhook endpoints](webhooks.md) |
| Exit | ends the flow for that customer |

Condition fields: `customer.segment`, `customer.churn_risk`,
`customer.orders`, `customer.revenue`, `customer.aov`, `customer.clv_12m`,
`customer.days_since_last_order`, `contact.locale`, `cart.item_count`,
`run.ordered_since_start`, and `event.<key>` for data the trigger carried.
`GET /flows/meta` returns the full list of triggers, fields and comparisons.

### Entry and exit rules

- A customer is in a flow at most once at a time.
- **Re-entry cooldown**: after entering, a customer cannot enter again for
  this many days (default 30).
- **Exit on order**: the customer leaves the flow as soon as they order. Turn
  it on for abandoned cart and win-back flows.

### Draft, publish, pause

Saving a flow keeps a draft and changes nothing that is live. **Publish**
checks the draft and turns it on. If you edit a live flow and publish again,
new customers get the new version and customers already inside finish the
one they started.

**Pause** stops new customers entering and holds everyone where they are.
Waits keep counting, so a customer whose wait ran out during the pause moves
on when you resume.

## Sending rules

Dashboard: **Automation → Sending**. API: `GET` / `PUT /email/settings`.

- **Quiet hours** in your timezone. An email due in that window waits until
  it ends.
- **Frequency cap**: the minimum number of hours between two emails to the
  same person, across all flows (default 16). An email that would arrive
  sooner is skipped.

Each email is checked again at the moment it is sent, not when the flow
queued it. If the customer unsubscribed, ordered or was erased during a
wait, the email is not sent, and the log says why.

## Results

**Automation → Email activity** lists every email with its status: queued,
sent, delivered, bounced, marked as spam, failed, or not sent with a reason.
`GET /email/messages` returns the same list.

Each flow shows how many customers entered, how many emails went out, opens,
clicks, and the orders and revenue that followed. An order is credited to the
last flow email the customer clicked in the five days before it. Product
clicks in a flow email also count as recommendation clicks on the Impact
page, under the `email` widget.

## What we store

- Contact details you sync: customer id, email, name, language, consent and
  signup date.
- A log of emails sent, without their content and without the address.
- Suppressed addresses, as one-way fingerprints rather than addresses.
- Discount codes issued to your customers, with their rules and the order
  ids that used them. Erasing a contact cancels their codes.

`DELETE /contacts/{customer_id}` erases a contact. If Email Flows is removed
from your plan, contacts and everything else listed here are deleted after
the grace period. You remain the controller of your customers' data, so add
Email Flows to your privacy policy.

## With the WooCommerce plugin

Version 0.5.0 and later sync contacts for you, and 0.6.0 and later accept a
separate discount code for each customer. Switch on **Sync contacts** in
the plugin settings. See the [WooCommerce Plugin](woocommerce-plugin.md#email-flows-contact-sync)
guide.

## With the OpenCart extension

Version 0.2.0 and later of the OpenCart 4 and OpenCart 3.0.x builds sync
contacts for you. Switch on **Sync contacts** on the extension's settings
page. See the [OpenCart Extension](opencart-plugin.md#email-flows-contact-sync)
guide.
