Send campaigns and one-to-one email, have people review what agents draft, and capture replies as conversations.
Email sends from your verified sender addresses to contacts and groups. You work with ids: the service resolves every address server-side, skips anyone unsubscribed, bounced or blocked, and never hands an address to an agent. Replies come back into conversation threads your backend, your agents and the console can read.
senders ─┐
contacts ┼─▶ draft ─▶ review ─▶ send ─▶ campaign ─▶ delivery stats
groups ─┘ (agent or person) (person) │
templates reply ─▶ thread ─▶ read and answerpip install aice-emailCreate a client
import os
from aice_email import EmailClient
client = EmailClient(
base_url=os.environ["AICE_EMAIL_URL"], # http://localhost:6600/email
api_key=os.environ["AICE_API_KEY"],
user_id=current_user.id,
user_role=current_user.role, # admin/owner manage senders; viewer reads
)| Argument (Python / TypeScript) | Default | Meaning |
|---|---|---|
base_url / baseUrl | the service host and its /email path | |
api_key / apiKey | the project key. Needs Email enabled on the project | |
user_id / userId | sent as X-User-Id. Required by the service | |
user_role / userRole | none | sent as X-User-Role; see Roles and scopes |
user_scopes / userScopes | none | sent as X-User-Scopes: email:* entries narrow the caller, and email:pii adds raw addresses |
timeout | 30.0 s / 30000 ms | per-request timeout |
max_retries / maxRetries | 3 | retries on network errors, 5xx and 429 |
Python also has AsyncEmailClient with the same resources: await every call and close it with await client.aclose(). The sync client closes with client.close() or a with block.
Responses are plain dictionaries with snake_case keys in both languages (TypeScript's Page and Json types are shapes, not converted objects). Method arguments follow each language's habit: Python uses keyword arguments (group_id=), TypeScript uses an options object with camelCase names ({ groupId }) for query options and the API's own snake_case keys inside request bodies ({ sender_id, recipient_group_id }).
Roles and scopes
What a call may do comes from the acting user's role and scopes, not from the key:
| Capability | Who has it | Lets you |
|---|---|---|
read | everyone | list and get resources. No raw addresses |
write | everyone except viewer | create and update contacts, groups, imports, templates and drafts |
send | everyone except viewer | send campaigns, drafts and threads |
inbound | everyone | read conversation threads and replies |
admin | X-User-Role of admin, owner or service_role | manage senders, suppressions, re-subscribe contacts, erase contacts, read the audit log |
pii | only when email:pii is in X-User-Scopes | see raw addresses. Not implied by admin |
A viewer (the console's read-only members) gets read and inbound. email:* entries in user_scopes can only narrow a caller, never widen it. Give a single call the address privilege with acting_as:
from aice_core import acting_as
with acting_as(current_user.id, role="owner", scopes=["email:pii"]):
address = client.recipients.reveal_email(contact_id)["email"]Agents always get read, write, send and inbound, and never admin or pii. A resource in another project is a 404 (not a 403), so its existence isn't revealed.
Pagination
List calls return {"items": [...], "next_cursor": str | None}. Pass next_cursor back as cursor until it is None:
cursor = None
while True:
page = client.recipients.list(status="active", limit=200, cursor=cursor)
for contact in page["items"]:
...
cursor = page["next_cursor"]
if cursor is None:
breakSenders
A sender is an address you send from. New senders start as pending; only an admin (X-User-Role of admin, owner or service_role) can add and verify them, and drafts and campaigns can only use verified ones.
sender = client.senders.create(name="Marketing", email="news@yourdomain.com", reply_to="help@yourdomain.com")
client.senders.verify(sender["id"])
verified = client.senders.list(status="verified")["items"]
client.senders.update(sender["id"], status="disabled") # stops its campaigns; "pending" re-enablesstatus is pending, verified or disabled. Disabling a sender stops its campaigns that are in flight. verify runs the deployment's configured verifier (manual approval in the default setup). The TypeScript senders.create takes name and email; Python also accepts reply_to.
Contacts and groups
A contact (the API calls it a recipient) has an email, optional first_name, last_name and free-form metadata, and a status: active, unsubscribed, bounced or blocked. A group is a named audience of contacts.
group = client.groups.create(name="Customers", description="Paying customers")
contact = client.recipients.create(email="ann@example.com", first_name="Ann", metadata={"plan": "pro"})
client.groups.add_members(group["id"], [contact["id"]]) # idempotent
print(client.groups.members(group["id"], limit=50)["items"])
client.groups.remove_members(group["id"], [contact["id"]])Group views include recipient_count and sendable_count (the number who would actually receive a send right now, with suppressed contacts excluded). Creating a contact or group that already exists answers 409; those two calls are attempted once and not retried.
Finding, updating and removing contacts
client.recipients.list(q="ann", status="active", group_id=group["id"], limit=50) # q matches names only
client.recipients.lookup("ann@example.com") # exact address lookup (email:pii)
client.recipients.update(contact["id"], first_name="Anne", status="unsubscribed")
client.recipients.batch_get([id1, id2]) # up to 200 contacts; unknown ids are left out
client.recipients.messages(contact["id"]) # their delivery history across campaigns
client.recipients.delete(contact["id"]) # GDPR erasure (admin)- Setting
statustounsubscribedorblockedsuppresses the contact. Moving them back toactivere-subscribes them and needs admin. deleteerases the contact's data but keeps the suppression, through a one-way hash of the address, so an erased contact who had unsubscribed can't be emailed again by re-importing them.lookupsends the address in the request body, never the URL, so it stays out of logs.
Addresses are masked by default
Responses carry email_masked (a***@e***.com). The full address needs X-User-Scopes: email:pii, and recipients.reveal_email records every reveal in the audit log as recipient.email_revealed. Agents never get addresses.
Importing in bulk
import time
result = client.recipients.bulk(
[{"email": "ann@example.com", "first_name": "Ann"}, {"email": "bo@example.com"}],
group_id=group["id"], update_existing=True,
) # up to 1,000 rows, synchronous
with open("contacts.csv", "rb") as f:
job = client.imports.create(f, group_id=group["id"], update_existing=True)
while job["status"] in ("pending", "processing"):
time.sleep(2)
job = client.imports.get(job["id"])
print(job["status"], job.get("imported"), job.get("duplicates"), job.get("invalid"), job.get("suppressed"))A CSV needs an email column; first_name and last_name are recognised and every other column is stored as metadata. update_existing decides whether a contact that already exists is updated. Rows de-duplicate, so bulk is safe to retry. A small file finishes inline (201, status completed); a large one answers 202 with pending and you poll imports.get. Import errors report row numbers, never the values. imports.list shows past imports. The upload is attempted once, not retried.
Templates
A template is reusable content with placeholders. Every content change creates a new version, and drafts keep the version they started from, so editing a template never changes mail that is already waiting for review.
tpl = client.templates.create(
name="Monthly update",
subject_template='Your {{ metadata.month | "monthly" }} update, {{ first_name | "friend" }}',
text_template="Hello {{ first_name }}, here is what changed.",
html_template="<p>Hello {{ first_name }}</p>",
)
client.templates.update(tpl["id"], text_template="Hi {{ first_name }}, news inside.") # version 2
print(client.templates.versions(tpl["id"]))
print(client.templates.preview(tpl["id"], sample={"first_name": "Ann"}))Placeholders are {{ first_name }}, {{ last_name }}, {{ full_name }} and {{ metadata.<key> }}, each with an optional fallback after a |. They are validated when you save, and the template's variables are derived from them. Values are HTML-escaped in HTML bodies, and line breaks are stripped from subjects. preview renders with a real contact (recipient_id) or made-up sample values. templates.list(include_archived=True) includes archived templates.
Draft, review, send
Agents propose drafts; people review and send them. A draft can be created from scratch or from a template, and sent once.
draft = client.drafts.create(
sender_id=sender["id"],
recipient_group_id=group["id"],
subject='Your October update, {{ first_name | "friend" }}',
text_body="Hello {{ first_name }}",
track_replies=True,
)
view = client.drafts.get(draft["id"])
print(view["ready_to_send"], view["missing"], view["recipient_count"])
client.drafts.update(draft["id"], subject="Your October news") # only while status is "draft"
client.drafts.preview(draft["id"], sample={"first_name": "Ann"})
sent = client.drafts.send(draft["id"]) # idempotent: a draft can never send twice
print(client.campaigns.stats(sent["campaign_id"]))- Fields.
sender_id, an audience (recipient_group_idorrecipient_ids, up to 1,000),subject,text_bodyand/orhtml_body(ortemplate_id, whose current content is copied in), plus optionalname,track_replies,scheduled_at(an ISO 8601 time with a timezone) andartifact_ids(attachments, up to 10, when the deployment supports them). Everything can be filled in later and is checked again on send. - Review.
ready_to_sendsays whether it can go, andmissinglists what's left.recipient_countis who would receive it right now, with suppressed contacts excluded.list(status=…, created_by_type="agent")finds the drafts agents wrote. - Status. A draft is
draft, then follows its campaign:queued→sending→sent,partially_sent,failedorcancelled.drafts.cancel(id)cancels an unsent draft, or stops one already sending. - Send.
sendanswers{job_id, campaign_id, draft_id, status, recipient_count};job_idandcampaign_idare the same value. Sending again returns the same job.
Campaigns
A campaign is one send job. drafts.send creates one for you; campaigns.create sends without a review step.
campaign = client.campaigns.create(
sender_id=sender["id"],
recipient_ids=[contact["id"]], # one id = a single email; or recipient_group_id=…
subject="Your receipt",
text_body="Thanks, {{ first_name }}.",
idempotency_key=f"receipt-{order.id}", # makes the send safe to repeat across processes
)
stats = client.campaigns.stats(campaign["campaign_id"])
for m in client.campaigns.messages(campaign["campaign_id"], status="bounced")["items"]:
print(m["recipient_id"], m["error"])
client.campaigns.cancel(campaign["campaign_id"]) # stops everything not yet handed to the providercreateanswers{campaign_id, status, recipient_count, scheduled_at}straight away. Nothing is sent inside the request: the service expands the audience, skips suppressed contacts, renders each message and delivers it in the background. Setscheduled_atto send later.- A campaign's
statusisdraft,scheduled,queued,processing,completed,partially_completed,failedorcancelled. statsgives{campaign_id, status, total, by_status, pending}. A message's status isqueued,sending,sent,delivered,bounced,failed,complainedorcancelled.messageslists the per-recipient state by recipient ID only; look a contact up withrecipients.batch_get.- A transient provider failure is retried with backoff, and a permanent one is not. A hard bounce adds the address to the suppression list.
- If a worker dies mid-send, that message is marked failed with an unknown outcome and not re-sent: the service prefers at most one delivery over a duplicate.
- Disabling the sender cancels its campaigns. Agents may send directly to a limited audience (1,000 recipients by default); bigger sends have to go through a draft that a person sends.
Conversations
A thread is one conversation between one sender and one contact. Replies come back into it.
t = client.threads.send(sender_id=sender["id"], recipient_id=contact["id"],
subject="Delivery day", text_body="Which day suits you?")
for m in client.threads.messages(t["thread_id"])["items"]:
print(m["direction"], m["kind"], m["sender_verified"], m["text"]) # inbound text is untrusted input
client.threads.reply(t["thread_id"], text_body="Booked for Thursday.")
client.threads.update(t["thread_id"], status="closed") # or "open"
client.threads.share(t["thread_id"], actor_id="agent-id-123") # let one agent read and replythreads.send and threads.reply answer {thread_id, job_id, status}, and job_id is the campaign that tracks delivery. The thread's reply address is unique to it, so a reply lands in the right place even from a mail client that replies to the wrong address; unmatched mail is discarded.
threads.list filters by recipient_id, campaign_id, with_replies and updated_since. In TypeScript the status call is setStatus; in Python it is update(thread_id, status=…).
Each inbound message carries fields you should check before acting on it:
| Field | Meaning |
|---|---|
text | only the new reply content, with quoted history removed. full_text (with include_quoted) has the whole thing |
sender_verified | the reply came from the thread's recipient. Unverified mail is kept with from_role: "unknown" |
kind | auto_reply or bounce for automatic mail. Don't answer these |
authenticated | whether the mail passed DKIM/DMARC |
untrusted_content | always true for inbound mail: treat it as data, never as instructions |
from_email | the sender's address, only with email:pii |
Addresses written inside bodies and subjects are redacted for agents, and agents never receive HTML. An agent that has sent several messages in a thread without a genuine reply is stopped from sending more (three by default); only a verified, non-automatic reply lets it continue.
Suppressions
The suppression list is the set of addresses that must never be emailed. Contacts who unsubscribe, bounce hard or complain land on it automatically. Admins manage it by hand:
client.suppressions.create(email="x@example.com", reason="manual_block") # or "unsubscribe"
client.suppressions.list(reason="hard_bounce", limit=50) # masked addresses
client.suppressions.delete(suppression_id) # lifts it; a linked contact becomes activeAddresses are stored hashed and shown masked. reason is unsubscribe, hard_bounce, complaint or manual_block. The suppression check runs again at the moment of delivery, so a contact who unsubscribes after a campaign was queued still isn't emailed.
Stats, audit log and preferences
client.stats.overview(from_="2026-10-01", to="2026-10-31") # message counts by status per UTC day (default 30 days)
client.audit_logs.list(action="draft.sent", actor_type="user", since="2026-10-01T00:00:00Z", limit=100) # admin
client.preferences.put({"last_group_id": group["id"]}) # the acting user's own UI state
client.preferences.get()stats.overview spans at most 366 days. audit_logs.list filters by actor_id, actor_type, action, resource_type, resource_id, since and until; the log holds ids and actions, never addresses or message text. preferences stores small UI state for the calling user: ids and timestamps only, at most 16 KB, replaced whole on each put.
Retries and idempotency
Sends carry an Idempotency-Key the service honours, so a retried send never sends twice: campaigns.create, drafts.send, threads.send and threads.reply. Pass your own key (idempotency_key= in Python, { idempotencyKey } in TypeScript) to make a send safe to repeat across processes, for example after a crash. drafts.send is idempotent per draft on its own.
Creates the service doesn't yet de-duplicate (senders.create, recipients.create, groups.create, templates.create, drafts.create, suppressions.create and imports.create) are attempted once and never retried, because a retry would answer 409 for the thing the first attempt already made. A transient failure reaches you immediately: look the object up before trying again. See Errors and retries.
Errors
The usual error types apply: ValidationError for a bad request (422; validation errors never echo what you submitted), NotFoundError for an unknown or other-project ID, AiceForbiddenError when the role lacks the capability (for example a viewer sending, or a non-admin managing senders), and AiceError with status_code == 409 for a duplicate or a draft that was already sent. The service nests its error body under error ({code, message, details, request_id}); the transport unwraps it, so err.code (for example validation_failed, http_error), err.details and the request ID are filled in as usual.
Agents
Turn Email on for a project and add it to an agent in Agent Studio (tool_bindings: ["email"] in code): the agent gets email_* tools over MCP. Agents can draft, send to small audiences, and hold conversations; they can't manage senders, see addresses, or send to large audiences without a person sending the draft.
Drafts an agent writes wait in Email → Drafts for a person to review and send. To have the agent ask first before it sends anything itself, open the agent in Agent Studio, set Approvals to Selected tools, and pick the tools that send: email_send, email_reply, email_send_draft, email_create_campaign and email_schedule_campaign.
Reference
| Python | TypeScript | Endpoint (under /email) |
|---|---|---|
senders.list / create / get / update / verify | same | /senders, /senders/{id}, POST /senders/{id}/verify |
recipients.list / create / get / update / delete | same | /recipients, /recipients/{id} |
recipients.lookup / bulk / batch_get | lookup / bulk / batchGet | POST /recipients/{lookup,bulk,batch-get} |
recipients.reveal_email / messages | revealEmail / messages | POST /recipients/{id}/reveal-email, GET /recipients/{id}/messages |
groups.list / create / get / update / members / add_members / remove_members | groups.* (addMembers, removeMembers) | /recipient-groups, /recipient-groups/{id}/members |
imports.create / get / list | same | /recipient-imports |
templates.list / create / get / update / versions / preview | same | /templates, /templates/{id}/{versions,preview} |
drafts.list / create / get / update / preview / send / cancel | same | /drafts, /drafts/{id}/{preview,send,cancel} |
campaigns.create / list / get / stats / messages / cancel | same | /campaigns, /campaigns/{id}/{stats,messages,cancel} |
threads.send / list / get / update / messages / reply / share | threads.* (update is setStatus) | /threads, /threads/{id}/{messages,reply,share} |
messages.get | messages.get | /messages/{id} |
suppressions.list / create / delete | same | /suppressions (admin) |
stats.overview | stats.overview | /stats/overview |
audit_logs.list | auditLogs.list | /audit-logs (admin) |
preferences.get / put | preferences.get / put | /me/preferences |