Send email from your application #
On this page
Prompt:
Email each customer a confirmation when their order ships.
Also works:
- "Send a receipt by email when a payment goes through."
- "Email a team member when someone invites them."
- "Why was our order email refused with
email_limit_reached?"
Send transactional email, such as order confirmations and invitations, from your application's backend. Declare the email service, use the Email package, and handle refusals by their code.
If someone asks for a sign-up confirmation, ask whether they mean the email code for sign-in or a welcome message after sign-up. Turn Zero sends the code when the app uses emailed-code sign-in. For a welcome message, have your backend record the completed registration and send once for that event. A later sign-in or page reload should leave that record alone.
What your AI does #
- Adds the email service to the manifest and submits the manifest again with
submit_manifest. - Takes the Email package from the library. It writes the backend's send with the package's client, as the sample in step 3 does. It tests the send with the package's test double.
- Reads the month's recipient count with
read_usage, and what happened to each message withread_countersandread_logs. - Asks you who receives each message and what it says, when the prompt does not say.
What you need #
- An application with a backend. Email is available to every application.
- The events that send a message, and who receives each one.
Before your AI starts #
For the AI assistant: Check the following before starting.
- A connected, signed-in AI assistant (Connect your AI assistant) and an application whose manifest has been submitted (Deploy from your computer).
- The application's identifier, from
list_applications.
Steps #
1. Read the charges and limits #
Every accepted recipient is charged to the account's balance. Read the current email rate on the pricing page, or call read_rate_card.
The starting limits are 100 recipients per UTC hour and 500 per UTC day. Development and production share these limits. Read the app's current limits with read_plan_quotas. Look for email-recipients-per-hour and email-recipients-per-day. The service is for occasional requests and notices. Use a mail provider of your own for newsletters or marketing mail.
For a weekly digest, agree on what it contains, who should receive it, and when it runs. Check that occasional account notices fit the built-in limits. For a newsletter, marketing mail, or a list beyond those limits, set up your own sender and key as described in step 4. Use Add a scheduled job to run the digest each week.
2. Declare the email service #
Add {"kind": "email"} to the manifest's services list, then submit the manifest again with submit_manifest. This line turns on email and sets up nothing else. You need no setting, no mail provider's key, and no domain of your own.
On Turn Zero's production platform, the sender is no-reply@mail.ai.host and the sender name is <application name> via mail.ai.host. On Turn Zero's development platform, the address is no-reply@mail.dev.ai.host and the name is <application name> via mail.dev.ai.host. Both environments of an application use the same mail domain.
When a message names a reply-to address, replies go there.
3. Send from the backend #
The backend sends with the Email package's client. Build the client once, from two settings your application receives: TURNZERO_CLOUD_API, the platform's address, and TURNZERO_CLOUD_APP_TOKEN, the platform credential. The credential identifies the application and its environment, so a send names neither. Your AI assistant adds the package as Use the feature package library describes.
This module emails a customer when their order ships. A test runs this sample over the Email package's test double and checks the send, the recipients counted, and a refused send.
// src/notify.mjs: emailShipped(customer, order) emails the customer that their order shipped.
import { createEmailClient, EmailRefusal } from '@turnzero/email';
// The platform's origin and this copy's credential, from the settings it receives.
const email = createEmailClient({ api: process.env.TURNZERO_CLOUD_API, token: process.env.TURNZERO_CLOUD_APP_TOKEN });
export async function emailShipped(customer, order) {
try {
const sent = await email.send({
to: [customer.email],
subject: `Order ${order.id} shipped`,
text: `Hello ${customer.name}, your order ${order.id} is on its way and arrives ${order.eta}.`,
replyTo: 'orders@example.com',
});
// A recipient count of zero means no message was queued.
return { messageId: sent.messageId, recipients: sent.recipients };
} catch (error) {
// Record the error without retrying; an unreadable answer leaves the send outcome unknown.
if (!(error instanceof EmailRefusal)) throw error;
const status = `HTTP ${error.status}`;
const detail = error.refusal === 'email_answer_unreadable' ? '' : error.detail;
console.error(`email send error ${error.refusal}: ${status}${detail ? ` ${detail}` : ''}`);
return error.resetsAt
? { refused: error.refusal, retryAt: error.resetsAt }
: { refused: error.refusal };
}
}
Use at least one valid to address. A message can have up to five recipients across to and cc. Repeating the same address text counts once. Give a nonempty one-line subject of up to 1,000 characters and a nonempty plain-text body, even if you include HTML. The subject and both bodies can use up to 256 KiB (262,144 bytes) together, counted as UTF-8. A message cannot carry a blind copy (bcc) or an attachment.
Send once for each event. The client never retries a send. If the platform accepted a send but its answer was lost, the message is already queued. A second send can queue another message and deliver a duplicate.
4. Handle a refused send #
A platform refusal such as email_limit_reached means the message was not queued. If the client reads a response it cannot interpret, it throws email_answer_unreadable. A network failure or an error reading the response can also leave the result unknown. In either case the message may already be queued. Do not send it again automatically.
After email_limit_reached, read period in the refusal details for the limit that blocked the send. The client's resetsAt gives the start of the next applicable UTC hour, day, or month. A plan without an application size can have a monthly limit. Hold the message until that time, or send it through your own mail provider.
Use your own mail provider for more mail than the limits allow. Use it too for mail this service does not send, such as newsletters or attachments. Declare the provider's HTTPS API as an upstream, an outside API your application may call, with your own key. Call an external API with an API key describes how.
5. Test the sends #
Your tests build the client over the package's test double, createEmailDouble from @turnzero/email/testing: pass double.transport as the client's transport, and read what was sent in double.sends. The double responds to a send as the platform does, using the email limits and the clock you configure for the test. It delivers nothing. Test your application locally runs the tests offline.
The platform skips every recipient at synthetic.turnzero.ai, the domain used for test end users. If every to address is skipped, any remaining cc addresses become the to recipients. Skipped addresses are excluded from recipients, usage counts, and charges. A paused account still receives its refusal.
The app still needs the email declaration and limits set above zero. A message with no remaining recipients uses none of that quota. If it passes and every address is skipped, the response is HTTP 202 with a message_id and recipients: 0. The package exposes the ID as messageId. A zero count means the platform queued no message.
For a digest, test which addresses the app selects before you test sending. Give the test a separate recipient list and check that it contains only test addresses. Use that list for manual tests and scheduled runs in development. The built-in service skips each synthetic address individually. Any real address still on the list can receive the message. Mail through your own provider does not pass through that filter. Use its test mode if it has one, or limit the list to an address you own.
Deploy the changed backend, then send once to an address you own. If development is on, deploy there first, check the send, and promote the tested version to production once the owner agrees.
Expected result #
- The send returns a
messageIdandrecipients, the number of addresses the platform accepted and counted. Withrecipients: 0, there is no delivery to wait for. The response confirms acceptance without waiting for the mail provider. It gives no delivery time. - The platform sends queued messages to its mail provider in the background. A provider can delay the queue. The platform counts each completed outcome under
email_sentoremail_failedand writes one log line withmessage_idandrecipients. Use the ID to find the message. A sent event means the provider accepted it. The log omits addresses. A test-only send produces neither event. See Read logs and counters. - For a failed message, the log's
failurefield gives the reason.refusedmeans the mail provider refused the message.exhaustedmeans three attempts failed.orphanedmeans the job picked up the message twice and each claim went stale without a recorded result. The record alone cannot tell what the provider did. - The mail provider blocks mail to an address that bounced earlier or whose recipient marked a message as spam. A message to that address ends
refused. The block applies across Turn Zero Cloud applications. read_usagereturns the month's recipients underemail_recipients, with the hour's and the day's counts beside it (Size and usage).- For a digest, check the schedule run and each send separately. Have the app save the result for each intended recipient with the digest it belongs to. Record the message ID and accepted count, the refusal, or that the outcome is unknown. Check delivery in an inbox you own. If the send outcome is unknown, check the saved results and your application's log stream before trying again.
Refusals #
See the refusals reference for other platform errors.
| Refusal | Status | Cause | Remedy |
|---|---|---|---|
email_not_declared |
409 | A send came from an application whose manifest does not declare the email service. | Add {"kind": "email"} to the manifest's services and submit it again. |
account_paused |
429 | The application's account is paused because its month's balance is used up. Nothing was queued. | A paused account resumes when it has Free Allowance available again or credit it can use. The client exposes the scheduled monthly reset as resetsAt. The Retry-After header gives the seconds until that reset. Check whether the account has resumed before sending again. |
email_limit_reached |
429 | The send would take the application past a recipient limit. The fields period, used, quota, requested, and resets_at name the limit and when sending is allowed again. |
Hold the message until resets_at, or send it through your own mail provider on a declared upstream. The client exposes that instant as resetsAt. |
plan_quantity_unset |
409 | A required email limit has no configured quantity. | Check the measure in the refusal and contact Turn Zero support about the missing limit. |
email_answer_unreadable |
As received | The response does not confirm whether the message was queued. | Leave automatic retries off because a repeat could deliver a duplicate. The send outcome stays unknown. read_usage gives totals. |
invalid_request |
400 | A field of the message is malformed, the message names a bcc or a sixth recipient, or it is too large. The detail names the field or the limit, never an address. |
Correct the named field. |
platform_credential_required |
403 | A send arrived under a session or a minted token. | Send from the backend under the platform credential. |
end_user_credential_not_admitted |
403 | A send arrived under the session of an end user, a person signed in to your application. | Send from the backend under the platform credential. |
Related #
- Size and usage reads the month's recipients.
- Call an external API with an API key sends mail through your own provider, past the application's limits.
- Read logs and counters explains how to read the email counters and lines.
- Test your application locally runs the tests on the packages' test doubles.
- Email describes the client, the message's fields, its refusals, and its test double.