Guides
Recipes
Small, complete examples of the jobs this API is for. Each uses the client module from Add it to your code, so the retries, timeouts and errors are already handled.
Booking confirmation#
HTML and text together, a reply-to address that reaches the front desk, and a key that ties the email to the booking.
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);
await sendEmail(
{
to: [`${booking.ownerName} <${booking.email}>`],
reply_to: 'booking@madagascarhotelags.com',
subject: `Booking confirmed: ${booking.petName}, ${booking.checkIn}`,
html: `<p>Hello ${esc(booking.ownerName)},</p>
<p><strong>${esc(booking.petName)}</strong> is booked from ${esc(booking.checkIn)} to ${esc(booking.checkOut)}.</p>
<p>Reply to this email if anything changes.</p>`,
text: `Hello ${booking.ownerName},\n\n${booking.petName} is booked from ${booking.checkIn} to ${booking.checkOut}.\nReply to this email if anything changes.`,
tags: ['booking', 'confirmation'],
},
{ key: `booking-${booking.id}-confirmation` },
);from html import escape
send_email(
{
"to": [f"{booking.owner_name} <{booking.email}>"],
"reply_to": "booking@madagascarhotelags.com",
"subject": f"Booking confirmed: {booking.pet_name}, {booking.check_in}",
"html": (
f"<p>Hello {escape(booking.owner_name)},</p>"
f"<p><strong>{escape(booking.pet_name)}</strong> is booked from "
f"{escape(booking.check_in)} to {escape(booking.check_out)}.</p>"
"<p>Reply to this email if anything changes.</p>"
),
"text": (
f"Hello {booking.owner_name},\n\n{booking.pet_name} is booked from "
f"{booking.check_in} to {booking.check_out}.\nReply to this email if anything changes."
),
"tags": ["booking", "confirmation"],
},
key=f"booking-{booking.id}-confirmation",
)Password reset#
Short, text first, and keyed on the reset request so a double click sends one email.
await sendEmail(
{
to: [user.email],
subject: 'Reset your password',
text: `Use this link within 30 minutes to choose a new password:\n${resetUrl}\n\nIf you did not ask for this, ignore this email.`,
tags: ['account', 'password-reset'],
},
{ key: `password-reset-${resetRequest.id}` },
);send_email(
{
"to": [user.email],
"subject": "Reset your password",
"text": f"Use this link within 30 minutes to choose a new password:\n{reset_url}\n\n"
"If you did not ask for this, ignore this email.",
"tags": ["account", "password-reset"],
},
key=f"password-reset-{reset_request.id}",
)Reminder the day before#
scheduled_at accepts times up to 72 hours ahead, so schedule a reminder from a daily job that looks at tomorrow's arrivals.
// Runs every day at 08:00: schedules a reminder for 18:00 the day before each arrival.
for (const booking of await bookingsArrivingTomorrow()) {
const sendAt = new Date(`${booking.checkInDate}T00:00:00-06:00`); // midnight in Aguascalientes
sendAt.setUTCHours(sendAt.getUTCHours() - 6); // 18:00 the evening before
await sendEmail(
{
to: [booking.email],
subject: `See you tomorrow, ${booking.petName}`,
text: 'Check-in opens at 9:00. Bring the vaccination record if it has changed.',
scheduled_at: sendAt.toISOString(),
tags: ['booking', 'reminder'],
},
{ key: `booking-${booking.id}-reminder` },
);
}from datetime import datetime, timedelta, timezone
for booking in bookings_arriving_tomorrow():
# 18:00 the evening before, in Aguascalientes (UTC-6).
send_at = datetime.combine(booking.check_in_date, datetime.min.time(), timezone(timedelta(hours=-6))) - timedelta(hours=6)
send_email(
{
"to": [booking.email],
"subject": f"See you tomorrow, {booking.pet_name}",
"text": "Check-in opens at 9:00. Bring the vaccination record if it has changed.",
"scheduled_at": send_at.isoformat(),
"tags": ["booking", "reminder"],
},
key=f"booking-{booking.id}-reminder",
)Tell the team#
One message to the team address, with a manager in copy. Each recipient counts against the shared allowance, so keep copies to the people who need them.
await sendEmail(
{
to: ['team@madagascarhotelags.com'],
cc: ['manager@example.com'],
subject: `New special-care request: ${request.petName}`,
text: `${request.ownerName} asked for: ${request.notes}`,
tags: ['staff', 'special-care'],
},
{ key: `care-request-${request.id}-staff` },
);send_email(
{
"to": ["team@madagascarhotelags.com"],
"cc": ["manager@example.com"],
"subject": f"New special-care request: {request.pet_name}",
"text": f"{request.owner_name} asked for: {request.notes}",
"tags": ["staff", "special-care"],
},
key=f"care-request-{request.id}-staff",
)Check for failures#
Without webhooks, a small periodic job is the reliable way to notice failed and dead messages. Check each recent message once, a minute or more after it was accepted.
// Every 10 minutes: look at messages accepted 1 to 60 minutes ago that are not final yet.
import { getMessage } from './email-client.mjs';
for (const row of await db.emails.pendingBetween('-60 minutes', '-1 minute')) {
const message = await getMessage(row.emailId);
if (['sent', 'failed', 'dead'].includes(message.status)) {
await db.emails.update(row.id, { status: message.status, error: message.error });
}
if (message.status === 'failed' || message.status === 'dead') {
await alertTeam(`Email ${message.id} ${message.status}: ${message.error}`);
}
}# Every 10 minutes: look at messages accepted 1 to 60 minutes ago that are not final yet.
from email_client import get_message
for row in db.emails.pending_between(minutes_ago=(60, 1)):
message = get_message(row.email_id)
if message["status"] in ("sent", "failed", "dead"):
db.emails.update(row.id, status=message["status"], error=message["error"])
if message["status"] in ("failed", "dead"):
alert_team(f"Email {message['id']} {message['status']}: {message['error']}")Handle a full day#
When 429 api_budget_reached or daily_cap_reached arrives, the next chance is after 00:00 UTC. Keep the message and try again then; the same key makes the retry safe even if the first attempt did get through.
try {
await sendEmail(message, { key });
} catch (err) {
if (err.code === 'api_budget_reached' || err.code === 'daily_cap_reached') {
await jobs.enqueue('send-email', { message, key }, { runAt: nextUtcMidnightPlus(5 /* minutes */) });
} else {
throw err;
}
}Last reviewed 2026-10-01.