Import your contacts with their consent, create a marketing template, send it to the people who agreed, follow the result per number, and follow up with those who replied or clicked.
You import your customer list, Meta approves one marketing template, and one API call per batch sends it. Each customer gets a WhatsApp message from your business name: "Hi John, our winter sale starts today: 20% off everything until Sunday." If they want no more offers, they reply STOP and never get another one.
app2email sends only to the people who may get it. Numbers on your Do Not Call list are skipped, and with the opt-in rule on, so is everyone without an opt-in record. You get the result for every number (accepted, delivered, read, replied, failed, skipped) as webhook events, from the API, as a CSV file, and on the broadcast's report page in the Activity Log.
GET /compliance/export.csv puts all three in one file.403 whatsapp_payment_issue).| Scope | What it is for in this guide |
|---|---|
contacts:manage | Import contacts, record consent, save segments (POST /contacts/import, POST /contacts/{identity}/consent, POST /segments) |
settings:manage | Turn on the opt-in rule and record opt-ins (PUT /settings/optin, POST /optins) |
dnc:manage | The Do Not Call list (POST /donotcall, GET /donotcall) and the compliance export |
templates:manage | Create the marketing template (POST /templates) |
messages:send | Send the broadcast, cancel it, send a follow-up (POST /messages, POST /broadcasts/{code}/cancel, POST /broadcasts/{code}/retarget) |
messages:read | Template status, segment contacts, broadcast results, clicks, usage, number health |
webhooks:manage | Add the webhook that receives the events (POST /webhooks) |
The Default key (made before keys had permissions) has only messages:send, messages:read, dnc:manage and webhooks:manage. Create a key with the scopes above, or with Full access (*). GET /v1/YOUR_NUMBER/me shows the scopes of the key you have.
Trying it first. A sandbox key on your own number (a key with the sandbox flag, on the API key page) checks every send for real and sends nothing to WhatsApp. The answer has "sandbox": true, message ids start with wamid.SANDBOX., and message.status events still arrive.
Take care: with a sandbox key, importing contacts, saving segments, opt-ins and the Do Not Call list change your real data. Creating templates, PUT /settings/optin and retargeting (except with dry_run) answer 403 sandbox_key.
With no account at all, POST https://api.app2email.com/v1/account/sandbox (no key, no body), or the create_sandbox tool of the Management MCP server, gives an instant sandbox key for the demo number 12025550100. It has the MARKETING template weekend_offer, and its pretend customer 12025550104 answers STOP: you get contact.opted_out, and the next marketing template to him answers 403 recipient_opted_out. That key has only a few calls (GET /templates, POST /messages, GET /events and a few more), so the contact and broadcast calls of this guide need a key on your own number. See Sandbox.
Send a CSV file with a header row. The columns app2email knows are phone (or identity, number, mobile), name (or first_name + last_name), tags (separated by |), consent_marketing (yes or no), consent_source, consent_text, consent_evidence, consent_at and source. Every other column becomes a custom field. Numbers have the country code first, digits only. Up to 5000 rows per call.
phone,name,first_name,tags,consent_marketing,consent_source,consent_text,consent_evidence,consent_at
61412345678,John Smith,John,vip|newsletter,yes,web form,"Yes, send me offers on WhatsApp",https://example.com/forms/123,2026-10-01T09:00:00Z
61498765432,Mary Jones,Mary,newsletter,yes,checkout,"Yes, send me offers on WhatsApp",order 5521,2026-10-12T02:30:00Zcurl -s https://api.app2email.com/v1/YOUR_NUMBER/contacts/import \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: text/csv" \
--data-binary @contacts.csvimport { readFile } from "node:fs/promises";
const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/contacts/import", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.A2E_KEY}`,
"Content-Type": "text/csv",
},
body: await readFile("contacts.csv"),
});
console.log(res.status, await res.json());import os, requests
with open("contacts.csv", "rb") as f:
res = requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/contacts/import",
headers={
"Authorization": f"Bearer {os.environ['A2E_KEY']}",
"Content-Type": "text/csv",
},
data=f,
)
print(res.status_code, res.json())What you get back: how many rows were saved, and the rows that were skipped with the reason. The rest are saved.
{
"success": true,
"request_id": "i2gka",
"rows": 120,
"saved": 118,
"created": 90,
"updated": 28,
"skipped": 2,
"errors": [
{
"row": 7,
"problem": "'0412' must be a WhatsApp number with country code, digits only (8 to 15 digits), or a business-scoped user id like 61.AbC123"
}
],
"note": "Rows with a problem were skipped (the first 50 are listed); the rest were saved."
}The same call takes application/json: a list of contacts in the format of POST /contacts. When someone agrees later (a web form, a checkbox at checkout), record it on the contact with its evidence:
curl -s https://api.app2email.com/v1/YOUR_NUMBER/contacts/61412345678/consent \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: application/json" \
-d '{
"marketing": true,
"source": "web form",
"text": "Yes, send me offers on WhatsApp",
"evidence": "https://example.com/forms/123"
}'Only record consent you really have.
The opt-in rule is a setting of the number. When it is on, MARKETING templates go only to numbers with an opt-in record. Everyone else is skipped with recipient_not_opted_in. Utility templates and replies are not affected. It is off by default.
Opt-in records are kept separately from the consent on a contact, so record each person who agreed here as well. Up to 1000 per call, all or nothing.
curl -s https://api.app2email.com/v1/YOUR_NUMBER/optins \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: application/json" \
-d '{
"numbers": [
{ "number": "61412345678", "name": "John", "source": "web form", "note": "ticked the box", "at": "2026-10-01T09:00:00Z" },
{ "number": "61498765432", "name": "Mary", "source": "checkout", "at": "2026-10-12T02:30:00Z" }
]
}'
curl -s -X PUT https://api.app2email.com/v1/YOUR_NUMBER/settings/optin \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: application/json" \
-d '{ "require_optin_for_marketing": true }'const headers = {
Authorization: `Bearer ${process.env.A2E_KEY}`,
"Content-Type": "application/json",
};
await fetch("https://api.app2email.com/v1/YOUR_NUMBER/optins", {
method: "POST",
headers,
body: JSON.stringify({
numbers: [
{ number: "61412345678", name: "John", source: "web form", note: "ticked the box", at: "2026-10-01T09:00:00Z" },
{ number: "61498765432", name: "Mary", source: "checkout", at: "2026-10-12T02:30:00Z" },
],
}),
});
await fetch("https://api.app2email.com/v1/YOUR_NUMBER/settings/optin", {
method: "PUT",
headers,
body: JSON.stringify({ require_optin_for_marketing: true }),
});headers = {"Authorization": f"Bearer {os.environ['A2E_KEY']}"}
requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/optins",
headers=headers,
json={
"numbers": [
{"number": "61412345678", "name": "John", "source": "web form", "note": "ticked the box", "at": "2026-10-01T09:00:00Z"},
{"number": "61498765432", "name": "Mary", "source": "checkout", "at": "2026-10-12T02:30:00Z"},
]
},
)
requests.put(
"https://api.app2email.com/v1/YOUR_NUMBER/settings/optin",
headers=headers,
json={"require_optin_for_marketing": True},
)What you get back: {"success": true, "request_id": "o9ahv", "saved": 2} for the opt-ins, and {"require_optin_for_marketing": true} for the setting. GET /v1/YOUR_NUMBER/optins?number=61412345678 checks one number (opted_in is true or false).
Marketing templates are never sent to a number on the Do Not Call list, whatever the opt-in records say. People who reply STOP are added by app2email itself. Add the ones who unsubscribed somewhere else (your shop, your email list, a phone call). Up to 1000 numbers, all or nothing.
curl -s https://api.app2email.com/v1/YOUR_NUMBER/donotcall \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: application/json" \
-d '{
"numbers": [
"61400111222",
{ "number": "61400333444", "name": "Sam", "note": "Unsubscribed in our CRM" }
]
}'const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/donotcall", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.A2E_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
numbers: ["61400111222", { number: "61400333444", name: "Sam", note: "Unsubscribed in our CRM" }],
}),
});
console.log(await res.json());res = requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/donotcall",
headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
json={"numbers": ["61400111222", {"number": "61400333444", "name": "Sam", "note": "Unsubscribed in our CRM"}]},
)
print(res.json())What you get back: the numbers added, the ones already_on_list, and how many are on the list now.
{
"success": true,
"request_id": "d4nca",
"added": ["61400111222", "61400333444"],
"already_on_list": [],
"count": 37
}GET /v1/YOUR_NUMBER/donotcall?number=61400111222 checks one number (on_list). DELETE /v1/YOUR_NUMBER/donotcall/61400111222 takes a number off the list: do that only when the person asked to get offers again.
Write the offer with a numbered placeholder for the first name, give a sample value for it in example, and add a footer that says how to stop. STOP and its translations are opt-out words app2email knows already.
curl -s https://api.app2email.com/v1/YOUR_NUMBER/templates \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "winter_sale",
"language": "en",
"category": "MARKETING",
"components": [
{
"type": "BODY",
"text": "Hi {{1}}, our winter sale starts today: 20% off everything until Sunday. Shop now: https://www.example.com/sale",
"example": { "body_text": [["John"]] }
},
{ "type": "FOOTER", "text": "Reply STOP to opt out" }
]
}'const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/templates", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.A2E_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "winter_sale",
language: "en",
category: "MARKETING",
components: [
{
type: "BODY",
text: "Hi {{1}}, our winter sale starts today: 20% off everything until Sunday. Shop now: https://www.example.com/sale",
example: { body_text: [["John"]] },
},
{ type: "FOOTER", text: "Reply STOP to opt out" },
],
}),
});
console.log(res.status, await res.json());res = requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/templates",
headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
json={
"name": "winter_sale",
"language": "en",
"category": "MARKETING",
"components": [
{
"type": "BODY",
"text": "Hi {{1}}, our winter sale starts today: 20% off everything until Sunday. Shop now: https://www.example.com/sale",
"example": {"body_text": [["John"]]},
},
{"type": "FOOTER", "text": "Reply STOP to opt out"},
],
},
)
print(res.status_code, res.json())What you get back (HTTP 201): the template is with Meta for review.
{
"success": true,
"request_id": "c3ppl",
"template": {
"id": "2234567890",
"name": "winter_sale",
"language": "en",
"category": "MARKETING",
"status": "PENDING"
},
"note": "Submitted to WhatsApp for review (minutes to a day). You get a template.status_changed webhook event with the result, or GET https://api.app2email.com/v1/4976659348270/templates/winter_sale."
}Review takes minutes to a day. The template.status_changed event tells you the result (status APPROVED with can_send: true, or REJECTED with a reason), or ask GET /v1/YOUR_NUMBER/templates/winter_sale. Its example_request is a complete send you can copy, and quality_score (GREEN, YELLOW or RED) shows later how people react to it. For the full review story see Send order and appointment notifications with templates.
Templates belong to the WhatsApp Business Account: every number on that account can use them.
A segment is a saved filter over your contacts. Every condition must hold: tags_any, tags_all, consent_marketing, last_inbound_days (wrote to you in the last N days) and search. Up to 100 segments.
curl -s https://api.app2email.com/v1/YOUR_NUMBER/segments \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Newsletter, consented",
"filter": { "tags_any": ["newsletter"], "consent_marketing": true }
}'const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/segments", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.A2E_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "Newsletter, consented",
filter: { tags_any: ["newsletter"], consent_marketing: true },
}),
});
const { segment } = await res.json();
console.log(segment.id, segment.contacts);res = requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/segments",
headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
json={"name": "Newsletter, consented", "filter": {"tags_any": ["newsletter"], "consent_marketing": True}},
)
segment = res.json()["segment"]
print(segment["id"], segment["contacts"])What you get back (HTTP 201): the segment, with how many contacts match now.
{
"success": true,
"request_id": "s5gmt",
"segment": {
"id": 12,
"name": "Newsletter, consented",
"filter": { "tags_any": ["newsletter"], "consent_marketing": true },
"contacts": 240,
"created": "2026-11-21T01:00:00Z",
"updated": "2026-11-21T01:00:00Z"
}
}GET /v1/YOUR_NUMBER/segments/12/contacts?limit=200 lists the contacts it matches, page by page (next_cursor). The segment is a filter, not a copy: a contact who withdraws consent drops out of it.
recipients gives each number its own values: here the first name from the import. Send one request per batch of up to max_numbers_per_request numbers (in GET /usage and GET /me; the broadcast limit, up to 1000).
"background": true answers as soon as everything is checked and sends after.campaign_name is the broadcast's name in the Activity Log under Broadcasts.Idempotency-Key header belongs to the batch: if your job runs twice within 24 hours, the batch is not sent again.curl -s https://api.app2email.com/v1/YOUR_NUMBER/messages \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: winter-sale-2026-batch-0" \
-d '{
"type": "template",
"campaign_name": "Winter sale 2026",
"background": true,
"template": { "name": "winter_sale", "language": { "code": "en" } },
"recipients": [
{
"to": "61412345678",
"components": [{ "type": "body", "parameters": [{ "type": "text", "text": "John" }] }]
},
{
"to": "61498765432",
"components": [{ "type": "body", "parameters": [{ "type": "text", "text": "Mary" }] }]
}
]
}'const BASE = "https://api.app2email.com/v1/YOUR_NUMBER";
const headers = {
Authorization: `Bearer ${process.env.A2E_KEY}`,
"Content-Type": "application/json",
};
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function call(path, init = {}) {
for (;;) {
const res = await fetch(BASE + path, { ...init, headers: { ...headers, ...init.headers } });
if (res.status === 429) {
const body = await res.json();
if (body.error.code !== "rate_limited") throw new Error(`${body.error.code}: ${body.error.how_to_fix}`);
await sleep(Number(res.headers.get("Retry-After") ?? 5) * 1000);
continue;
}
const body = await res.json();
if (!res.ok) throw new Error(`${body.error.code}: ${body.error.how_to_fix}`);
return body;
}
}
// 1. Everyone the segment matches, page by page
const contacts = [];
let cursor = "";
do {
const page = await call(`/segments/12/contacts?limit=200${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`);
contacts.push(...page.contacts);
cursor = page.next_cursor;
} while (cursor);
// 2. The most numbers per request
const { max_numbers_per_request: max } = await call("/usage");
// 3. One request per batch, each with its own Idempotency-Key
for (let i = 0, n = 0; i < contacts.length; i += max, n++) {
const batch = contacts.slice(i, i + max);
const body = await call("/messages", {
method: "POST",
headers: { "Idempotency-Key": `winter-sale-2026-batch-${n}` },
body: JSON.stringify({
type: "template",
campaign_name: `Winter sale 2026 (${n + 1})`,
background: true,
template: { name: "winter_sale", language: { code: "en" } },
recipients: batch.map((c) => ({
to: c.identity,
components: [
{ type: "body", parameters: [{ type: "text", text: c.custom_fields?.first_name || c.name || "there" }] },
],
})),
}),
});
if (body.status === "pending_approval") console.log("waiting for approval:", body.approval.url);
else console.log(body.status, body.broadcast.code, body.queued, body.skipped);
}import os, time, requests
BASE = "https://api.app2email.com/v1/YOUR_NUMBER"
HEADERS = {"Authorization": f"Bearer {os.environ['A2E_KEY']}"}
def call(method, path, **kw):
while True:
res = requests.request(method, BASE + path, headers={**HEADERS, **kw.pop("headers", {})}, **kw)
body = res.json()
if res.status_code == 429 and body["error"]["code"] == "rate_limited":
time.sleep(int(res.headers.get("Retry-After", "5")))
continue
if not res.ok:
raise RuntimeError(f"{body['error']['code']}: {body['error']['how_to_fix']}")
return body
# 1. Everyone the segment matches, page by page
contacts, cursor = [], None
while True:
page = call("GET", "/segments/12/contacts", params={"limit": 200, **({"cursor": cursor} if cursor else {})})
contacts += page["contacts"]
cursor = page.get("next_cursor")
if not cursor:
break
# 2. The most numbers per request
size = call("GET", "/usage")["max_numbers_per_request"]
# 3. One request per batch, each with its own Idempotency-Key
for n, i in enumerate(range(0, len(contacts), size)):
batch = contacts[i : i + size]
body = call(
"POST",
"/messages",
headers={"Idempotency-Key": f"winter-sale-2026-batch-{n}"},
json={
"type": "template",
"campaign_name": f"Winter sale 2026 ({n + 1})",
"background": True,
"template": {"name": "winter_sale", "language": {"code": "en"}},
"recipients": [
{
"to": c["identity"],
"components": [
{
"type": "body",
"parameters": [
{"type": "text", "text": c.get("custom_fields", {}).get("first_name") or c.get("name") or "there"}
],
}
],
}
for c in batch
],
},
)
if body["status"] == "pending_approval":
print("waiting for approval:", body["approval"]["url"])
else:
print(body["status"], body["broadcast"]["code"], body.get("queued"), body.get("skipped"))What you get back (HTTP 202): the checks passed and sending has started. Keep broadcast.code: every later call about this broadcast uses it.
{
"success": true,
"request_id": "t7wpe",
"status": "queued",
"from": "4976659348270",
"template": { "name": "winter_sale", "language": "en", "category": "MARKETING" },
"broadcast": {
"name": "Winter sale 2026",
"code": "k3XbQ9rTzP2mWv7a1c9e",
"report_url": "https://www.app2email.com/dashboard/log/broadcast/k3XbQ9rTzP2mWv7a1c9e",
"status_url": "https://api.app2email.com/v1/4976659348270/broadcasts/k3XbQ9rTzP2mWv7a1c9e"
},
"recipients": 2,
"queued": 2,
"skipped": 0,
"results": [],
"note": "Sending in the background. GET broadcast.status_url for progress and the result for each number, or use the broadcast.completed webhook."
}Every number is checked before anything is sent. Numbers on the Do Not Call list, and (with the opt-in rule on) numbers without an opt-in record, are skipped and counted, not sent.
Test first. Add "dry_run": true to the same body. Everything is checked as for a real send (template values, numbers, the Do Not Call list, the opt-in rule, the monthly limit) and the answer shows the exact WhatsApp message per number. Nothing is sent, logged or counted, and the Idempotency-Key is ignored.
Straight to the segment. "segment": "Newsletter, consented" (its id or exact name) instead of recipients sends to every contact of the segment in one call. Values come from each contact for a template with named placeholders ({{first_name}}, created with "parameter_format": "NAMED"): a parameter with a parameter_name and no text is filled from the contact's custom_fields (name from the contact's name).
{
"segment": "Newsletter, consented",
"type": "template",
"campaign_name": "November offer",
"template": {
"name": "november_offer",
"language": { "code": "en" },
"components": [
{ "type": "body", "parameters": [{ "type": "text", "parameter_name": "first_name" }] }
]
}
}Add send_at (ISO 8601 with a time zone, 1 minute to 29 days ahead) to the same body. Morning in your customers' time zone usually works better than the middle of the night.
{
"type": "template",
"campaign_name": "Winter sale 2026",
"template": { "name": "winter_sale", "language": { "code": "en" } },
"recipients": [
{ "to": "61412345678", "components": [{ "type": "body", "parameters": [{ "type": "text", "text": "John" }] }] }
],
"send_at": "2026-12-01T09:00:00+11:00"
}The answer is HTTP 202 with status: "scheduled", scheduled_for (UTC), scheduled (how many messages) and the broadcast code. Everything is checked at once, and the Do Not Call list and the monthly limit are checked again when the time comes, so someone who says STOP in between does not get it.
GET /v1/YOUR_NUMBER/broadcasts/{code} is live while the broadcast sends.
curl -s https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7a1c9e \
-H "Authorization: Bearer $A2E_KEY"
# one row per message, for a spreadsheet
curl -s https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7a1c9e/results.csv \
-H "Authorization: Bearer $A2E_KEY" -o winter-sale.csvconst res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7a1c9e", {
headers: { Authorization: `Bearer ${process.env.A2E_KEY}` },
});
const { broadcast, counts } = await res.json();
console.log(broadcast.status, counts);res = requests.get(
"https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7a1c9e",
headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
)
body = res.json()
print(body["broadcast"]["status"], body["counts"])What you get back: the broadcast, its counts and one result per number. status is scheduled, inprogress, completed, cancelled, missed, interrupted, pending or unknown. Each result is the message (with status, times and the customer's reply), or skipped, not_sent or pending with a reason.
{
"success": true,
"request_id": "b6rsl",
"broadcast": {
"code": "k3XbQ9rTzP2mWv7a1c9e",
"name": "Winter sale 2026",
"created": "2026-12-01T09:00:00Z",
"status": "completed",
"sent_by": "api",
"template": { "name": "winter_sale", "language": "en" },
"report_url": "https://www.app2email.com/dashboard/log/broadcast/k3XbQ9rTzP2mWv7a1c9e"
},
"counts": {
"numbers": 240,
"skipped_do_not_call": 3,
"skipped_monthly_limit": 0,
"posted": 237,
"accepted": 236,
"sent": 236,
"delivered": 229,
"read": 171,
"failed": 1,
"replied": 19,
"opted_out": 2
},
"results": [
{
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
"to": "61412345678",
"status": "read",
"sent_by": "api",
"broadcast_code": "k3XbQ9rTzP2mWv7a1c9e",
"text": "Hi John, our winter sale starts today: 20% off everything until Sunday. Shop now: https://www.example.com/sale",
"times": {
"submitted": "2026-12-01T09:00:00Z",
"accepted": "2026-12-01T09:00:01Z",
"sent": "2026-12-01T09:00:02Z",
"delivered": "2026-12-01T09:00:04Z",
"read": "2026-12-01T09:14:40Z"
},
"reply": { "at": "2026-12-01T09:15:10Z", "text": "Do you have it in blue?" },
"conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_..."
},
{ "to": "61400111222", "status": "skipped", "reason": "On the Do Not Call list" }
]
}results.csv has one row per message: the number, status, message_id, the time of each step, the reply and the error (plus clicks and first_click_at when links were tracked). Values that start with =, +, - or @ get a ' in front, so a spreadsheet does not run them as formulas. GET /v1/YOUR_NUMBER/broadcasts lists your latest broadcasts, newest first.
Wrong price in the offer? POST /v1/YOUR_NUMBER/broadcasts/{code}/cancel (scope messages:send) stops an API broadcast that is scheduled or still sending.
curl -s -X POST https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7a1c9e/cancel \
-H "Authorization: Bearer $A2E_KEY"const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7a1c9e/cancel", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.A2E_KEY}` },
});
console.log(res.status, await res.json());res = requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7a1c9e/cancel",
headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
)
print(res.status_code, res.json())What you get back: HTTP 200 for a scheduled broadcast (nothing was sent), or HTTP 202 for one that is sending: messages already handed to WhatsApp stay sent, the rest are not sent.
{
"success": true,
"request_id": "u1nqd",
"broadcast": { "code": "k3XbQ9rTzP2mWv7a1c9e", "status": "cancelling" },
"note": "Cancelling. Messages already handed to WhatsApp stay sent; the rest are not sent. GET https://api.app2email.com/v1/4976659348270/broadcasts/k3XbQ9rTzP2mWv7a1c9e shows the result."
}A broadcast.completed event follows with status: "cancelled". Finished broadcasts, and broadcasts started from the dashboard, answer 409 broadcast_not_cancellable.
An API broadcast: build the next list yourself from the result. Each result in GET /broadcasts/{code} has the message status and the customer's reply, so you can pick, for example, everyone who read the offer and did not answer, and send them a second template with POST /messages as above.
const { results } = await (await fetch(`${BASE}/broadcasts/k3XbQ9rTzP2mWv7a1c9e`, { headers })).json();
const readNoReply = results.filter((r) => r.status === "read" && !r.reply).map((r) => r.to);A broadcast started on the dashboard's Broadcast page has two more things the API can use:
https://www.app2email.com/l/<code> for a link in the broadcast's values. GET /broadcasts/{code}/clicks gives the total, the unique clicks, the click rate and each recipient's clicks (link previews and crawlers are not counted). The same figures are in clicks of GET /broadcasts/{code}, and a link.clicked event arrives for every click.POST /broadcasts/{code}/retarget makes a new broadcast with the same template, values and media, for one audience: not_read, read_not_clicked, clicked, replied (wrote back within 7 days of the send) or not_replied. Count first with dry_run:curl -s https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7/retarget \
-H "Authorization: Bearer $A2E_KEY" \
-H "Content-Type: application/json" \
-d '{ "audience": "read_not_clicked", "dry_run": true }'const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7/retarget", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.A2E_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ audience: "read_not_clicked", dry_run: true }),
});
console.log(await res.json());res = requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/broadcasts/k3XbQ9rTzP2mWv7/retarget",
headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}"},
json={"audience": "read_not_clicked", "dry_run": True},
)
print(res.json())What you get back: with dry_run, the count (HTTP 200). Without it, HTTP 202 and the new broadcast, which sends in the background.
{
"success": true,
"request_id": "c3rtg",
"audience": "read_not_clicked",
"recipients": 131,
"broadcast": {
"code": "Mx8Pq2Lw5Rt7Yz3",
"name": "Summer sale - read not clicked",
"status": "inprogress",
"status_url": "https://api.app2email.com/v1/4976659348270/broadcasts/Mx8Pq2Lw5Rt7Yz3",
"report_url": "https://www.app2email.com/dashboard/log/broadcast/Mx8Pq2Lw5Rt7Yz3"
},
"note": "The new broadcast is sending in the background."
}The Do Not Call list and the plan limit are checked again, and the key's approval limit and daily cap apply. Retarget, resume and retry work on dashboard broadcasts only: an API list answers 403 broadcast_not_resumable.
A follow-up is another marketing message, billed again. Send it to a small, interested group (clicked, replied), not to everyone who ignored the first one.
The customer sees a message from your business name with the offer, their first name in it and the footer "Reply STOP to opt out". If they reply, the 24-hour window opens and you can answer in free text from the API or by email.
On your side these events arrive (add a webhook with POST /v1/YOUR_NUMBER/webhooks and a public https url; scope webhooks:manage). No public address yet? GET /v1/YOUR_NUMBER/events?wait=25 gives the same events.
message.status for every message, as it moves on: sent, delivered, read, or failed. broadcast_code says which broadcast it belongs to, and pricing.category how Meta counted it.
{
"id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
"type": "message.status",
"created": "2026-12-01T09:00:04.000Z",
"number": "4976659348270",
"data": {
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
"to": "61412345678",
"status": "delivered",
"timestamp": "2026-12-01T09:00:04.000Z",
"sent_by": "api",
"broadcast_code": "k3XbQ9rTzP2mWv7a1c9e",
"whatsapp_status": "delivered",
"recipient_user_id": "AU.1234567890123456",
"pricing": { "billable": true, "pricing_model": "PMP", "type": "regular", "category": "marketing" }
}
}message.failed when a message could not be delivered. One you will see with marketing is Meta error 131049: WhatsApp held the message back because the person has had many marketing messages lately. Do not send it again within 24 hours; retrying sooner keeps the block longer.
{
"id": "evt_Pa3k9m2Lw8Rt5Yp1Zs011",
"type": "message.failed",
"created": "2026-12-01T09:00:03.000Z",
"number": "4976659348270",
"data": {
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
"to": "61412345678",
"status": "failed",
"timestamp": "2026-12-01T09:00:03.000Z",
"sent_by": "broadcast",
"whatsapp_status": "failed",
"error": {
"code": 131049,
"message": "This message was not delivered to maintain healthy ecosystem engagement.",
"title": "This message was not delivered to maintain healthy ecosystem engagement.",
"error_code": "marketing_per_user_limit",
"how_to_fix": "WhatsApp held this marketing message back: the person has had many marketing messages lately. Do not send it again within 24 hours, because retrying sooner keeps the block longer.",
"is_retriable": false,
"retry_after_seconds": 86400
}
}
}message.received when a customer answers: text for a typed reply, button for a tapped button.
contact.opted_out when a customer put themselves on the Do Not Call list. source is stop_promotions (they tapped "Stop promotions"), whatsapp_stop or keyword (they sent an opt-out word).
{
"id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
"type": "contact.opted_out",
"created": "2026-12-01T09:20:00.000Z",
"number": "4976659348270",
"data": {
"number": "61412345678",
"name": "John Smith",
"source": "stop_promotions",
"detail": "Stop promotions",
"timestamp": "2026-12-01T09:20:00.000Z"
}
}link.clicked for every click on a tracked link (dashboard broadcasts). first_click is true for the first click of that recipient's link.
{
"id": "evt_Cmp3k9m2Lw8Rt5Yp1Zs01",
"type": "link.clicked",
"created": "2026-11-19T01:00:00.000Z",
"number": "4976659348270",
"data": {
"contact": "61412345678",
"url": "https://example.com/sale",
"broadcast_code": "k3XbQ9rTzP2mWv7",
"sequence_id": null,
"step_id": null,
"first_click": true,
"clicks": 1,
"browser": "Chrome",
"timestamp": "2026-11-19T01:00:00.000Z"
}
}broadcast.completed once per broadcast, when it finished, was cancelled or missed its scheduled time.
{
"id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
"type": "broadcast.completed",
"created": "2026-12-01T09:04:00.000Z",
"number": "4976659348270",
"data": {
"code": "k3XbQ9rTzP2mWv7a1c9e",
"name": "Winter sale 2026",
"status": "completed",
"sent_by": "api",
"numbers": 240,
"posted": 237,
"accepted": 236,
"errors": 1,
"skipped_do_not_call": 3,
"skipped_monthly_limit": 0,
"status_url": "https://api.app2email.com/v1/4976659348270/broadcasts/k3XbQ9rTzP2mWv7a1c9e",
"report_url": "https://www.app2email.com/dashboard/log/broadcast/k3XbQ9rTzP2mWv7a1c9e"
}
}GET /v1/YOUR_NUMBER/stats?from=&to= adds up sent, delivered, read, failed and replied counts and rates for a period, across broadcasts.
Two bills:
skipped_monthly_limit) or answers 429 monthly_limit_reached.Estimate it before you send with the WhatsApp pricing calculator. Afterwards, meta_pricing in GET /v1/YOUR_NUMBER/usage counts the billing month's messages by Meta's category with an indicative cost, and GET /v1/YOUR_NUMBER/usage/meta gives it per day.
Once Meta has onboarded your account to its Marketing Messages API, marketing templates go that way by default (the number's setting messages.marketing_route, auto). GET /v1/YOUR_NUMBER/marketing shows the route, and the send answer's sent_via says which way a message went. Nothing changes in your request.
WhatsApp watches how people react to your messages. Many blocks and reports lower your quality rating. Then:
quality_score (in GET /templates/{name}) turns YELLOW, then RED, and a RED template can be paused (422 template_paused, Meta error 132015);paused_by_meta, with the reason in status_notes); fix the cause and POST /broadcasts/{code}/resume carries on.GET /v1/YOUR_NUMBER/health (scope messages:read) shows the number's quality_rating and messaging_limit:
{
"success": true,
"request_id": "h7q2m",
"health": {
"can_send_message": "AVAILABLE",
"quality_rating": "GREEN",
"messaging_limit": "TIER_2K",
"throughput": "STANDARD",
"status": "CONNECTED",
"name_status": "APPROVED",
"account_mode": "LIVE"
},
"fetched_at": "2026-11-06T01:00:00.000Z"
}How to keep it green:
last_inbound_days in the segment filter) and watch reads and opt-outs on the first part before you send the rest.Every event has the header X-App2email-Signature: t=<unix seconds>,v1=<hex>. The v1 value is the HMAC-SHA256 of "<t>.<raw body>", with the webhook's secret (whsec_..., prefix included) as the key. Check every v1= (there are two while an old secret is still kept after a rotation), compute it over the raw body exactly as received, and refuse an old t. X-Hub-Signature-256: sha256=<hex> (HMAC-SHA256 of the raw body, current secret only) is there too, for code written for Meta's webhooks.
import crypto from "node:crypto";
import express from "express";
export function verifyWebhook(rawBody, header, secret, toleranceSeconds = 300) {
const t = /(?:^|,)\s*t=(\d+)/.exec(header ?? "")?.[1];
const v1 = [...(header ?? "").matchAll(/(?:^|,)\s*v1=([0-9a-f]+)/g)].map((m) => m[1]);
if (!t || v1.length === 0 || Math.abs(Date.now() / 1000 - Number(t)) > toleranceSeconds) return false;
const expected = crypto.createHmac("sha256", secret).update(t + ".").update(rawBody).digest("hex");
return v1.some((v) => v.length === expected.length && crypto.timingSafeEqual(Buffer.from(v), Buffer.from(expected)));
}
const app = express();
app.post("/app2email", express.raw({ type: "application/json" }), async (req, res) => {
if (!verifyWebhook(req.body, req.get("X-App2email-Signature"), process.env.WEBHOOK_SECRET)) return res.sendStatus(401);
if (await alreadySeen(req.get("X-App2email-Delivery"))) return res.sendStatus(200); // a retry
const event = JSON.parse(req.body);
res.sendStatus(200); // answer within 10 seconds, then do the work
switch (event.type) {
case "message.status":
case "message.failed":
await saveStatus(event.data.broadcast_code, event.data.to, event.data.message_id, event.data.status, event.data.error);
break;
case "contact.opted_out":
await markUnsubscribed(event.data.number, event.data.source); // in your CRM too
break;
case "broadcast.completed":
await saveBroadcastTotals(event.data);
break;
}
});import hashlib, hmac, json, os, re, time
from flask import Flask, request
def verify_webhook(raw_body: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
t = re.search(r"(?:^|,)\s*t=(\d+)", header or "")
v1 = re.findall(r"(?:^|,)\s*v1=([0-9a-f]+)", header or "")
if not t or not v1 or abs(time.time() - int(t.group(1))) > tolerance:
return False
expected = hmac.new(secret.encode(), t.group(1).encode() + b"." + raw_body, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(v, expected) for v in v1)
app = Flask(__name__)
@app.post("/app2email")
def app2email():
raw = request.get_data()
if not verify_webhook(raw, request.headers.get("X-App2email-Signature"), os.environ["WEBHOOK_SECRET"]):
return "", 401
if already_seen(request.headers.get("X-App2email-Delivery")):
return "", 200 # a retry
event = json.loads(raw)
queue.put(event) # handle it after answering
return "", 200 # within 10 secondsAnswer with a 2xx status within 10 seconds. Otherwise the event is sent again after 10 s, 1 min, 5 min, 30 min, 1, 2, 4, 8 and 16 hours. X-App2email-Delivery (the event id, evt_...) is the same on every retry, so store it and skip an event you already handled.
Events can arrive out of order: a read may come before its delivered. Keep the furthest status per message_id and do not move it back. For a broadcast, key your records by broadcast_code and to.
Give each batch an Idempotency-Key that belongs to the campaign and the batch, not to the attempt: winter-sale-2026-batch-0, winter-sale-2026-batch-1. The same request with the same key within 24 hours is not sent again; it gets the first answer, with the header Idempotent-Replayed: true.
422 idempotency_key_reused. Keep the batches in the same order, or use new keys for a new list.409 idempotency_request_in_progress. Wait and retry with the same key.409 idempotency_request_interrupted. Some messages may have gone out: check GET /broadcasts before you send with a new key.The key is kept for 24 hours. Also keep each batch's broadcast.code in your database and do not send a batch that already has one.
Send a list in one call per batch, not one call per number. Every answer has X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset (seconds until full again) and X-RateLimit-Policy; limits in GET /me shows the key's requests_per_second and burst. Over the limit you get 429 rate_limited with a Retry-After header and error.retry_after_seconds: wait that long, then send the same request again.
500, 502, 503 or a timeout: retry a few times with growing waits, with the same Idempotency-Key.429 whatsapp_rate_limit or 429 too_many_messages_to_recipient: WhatsApp's own limit. Back off for minutes, not seconds.429 monthly_limit_reached, 429 monthly_cap_reached or 429 daily_cap_reached: a limit of the plan, the number or the key. Do not retry until it resets, or raise it.4xx: do not retry unchanged. Decide by error.code and follow how_to_fix. error.is_retriable tells you whether the same request can work later.A key can have a daily cap and an approval gate (GET /me shows them). A send to more contacts than the gate allows answers HTTP 202 with status: "pending_approval" and approval.url: it is not an error. A person approves it on the dashboard, the approval.resolved event follows, and the messages go out. Do not send the same list another way meanwhile. This is a good safety net for a key that sends marketing.
contact.opted_out tells you. Add your own opt-out words with PUT /v1/YOUR_NUMBER/settings/number and {"compliance": {"stop_keywords_extra": ["UNSUBSCRIBE"]}} (scope settings:manage).POST /contacts/{identity}/consent with "marketing": false), so segments with consent_marketing: true leave them out, and put them on the Do Not Call list if they unsubscribed elsewhere.403 recipient_stopped_marketing (Meta error 131050). If they turn it back on, contact.updated arrives with change: "marketing_resumed".GET /v1/YOUR_NUMBER/compliance/export.csv (scope dnc:manage) gives the consent records, the Do Not Call list and the opt-ins as one file, the records the Spam Act 2003 expects you to be able to show.A broadcast is a template, so it can go out at any time. When a customer replies, the 24-hour window opens and you can answer with normal text, pictures or buttons (app2email stops 15 minutes early). GET /v1/YOUR_NUMBER/conversations/61412345678 shows window_state and window_closes_at. If their last message was the opt-out itself, a reply answers 403 recipient_opted_out until they write again.
Every error is JSON with error.code, message, how_to_fix and a request_id to quote to support. See Errors for every code and Limits for the limits.
| Code | When | What to do |
|---|---|---|
403 insufficient_scope | The key lacks a scope (details.required_scope) | Use a key with the scopes in the table above |
403 sandbox_key | A template, PUT /settings/optin or a retarget with a sandbox key | Use a normal key for those calls |
400 invalid_csv | The CSV has no header row or no contact row | Send a header row and at least one row, up to 5000 rows |
400 invalid_template_category | category is not MARKETING, UTILITY or AUTHENTICATION | Use MARKETING for promotions |
422 template_not_approved | The template is pending, rejected, paused or disabled | Wait for approval, or fix it; check GET /templates/{name} |
422 template_parameters_invalid | The values do not match the template | Fix the body from details.problems and example_request |
422 template_paused | Meta error 132015: paused for low quality | Use another template, or edit this one; send to fewer, better-matched people |
400 too_many_recipients | More numbers than the number may send in one request | Split into batches of details.max_recipients |
400 to_and_recipients | Both to and recipients | Use one of them |
400 segment_and_recipients | segment together with to, recipient or recipients | Use only segment |
400 segment_empty | The segment matches no contacts | Check GET /segments/{id}/contacts, add contacts or change the filter |
404 segment_not_found | No segment with that id or name | GET /segments lists them; use the id or the exact name |
403 recipient_opted_out | One number, and it is on the Do Not Call list | Do not send them marketing; in a list it is skipped |
403 recipient_not_opted_in | One number, the opt-in rule is on and it has no opt-in record | Record their consent first with POST /optins; in a list it is skipped |
403 recipient_stopped_marketing | Meta error 131050: they turned off your marketing in WhatsApp | Do not send them marketing templates |
422 marketing_per_user_limit | Meta error 131049: they had many marketing messages lately | Do not resend within 24 hours |
403 messaging_limit_restricted | Meta error 131064: Meta lowered the messaging limit for wrong template categories | Check your template categories; the limit comes back after Meta's period |
403 whatsapp_payment_issue | Meta error 131042: Meta could not charge your WhatsApp account | Add or fix the payment method in WhatsApp Manager |
400 send_at_too_far | send_at is more than 29 days ahead | Use a time 1 minute to 29 days from now, with a time zone |
422 idempotency_key_reused | Same Idempotency-Key, different body | Use a new key for a different list |
429 rate_limited | Too many calls for this key | Wait Retry-After seconds, then retry |
429 whatsapp_rate_limit | WhatsApp's rate limit (Meta 130429, 131048 and others) | Slow down and try again in a minute or more |
429 monthly_limit_reached | The plan's messages are used up this month | Wait for the next billing month, or upgrade |
429 daily_cap_reached | The key's daily cap | Wait until midnight UTC, or raise the cap |
409 broadcast_not_cancellable | The broadcast is finished, already cancelled, or was started on the dashboard | Only API sends that are scheduled or still sending can be cancelled |
403 broadcast_not_resumable | Retarget, resume or retry on an API list | For an API list, send the numbers you want again with POST /messages |
400 invalid_retarget_audience | audience is not one of the five values | Use not_read, read_not_clicked, clicked, replied or not_replied |
409 broadcast_nothing_to_send | Nobody left in that audience | Nothing to do |
403 campaign_approval_needed | A retarget would send more than the key's approval limit | Start it from the dashboard, or use a key without an approval limit |
Receive messages by webhook and answer with text, buttons and lists.
A utility template for each order or booking, with delivery and read status.
Connect an agent to the MCP server and let it read and send messages.
Set the conversation owner so your bot steps aside while a person answers.
Send a payment request in the chat and get an event when it is paid.