Guides
Add it to your code
Most integrations need the same seven decisions and one small module. Make the decisions once, drop the module into your codebase, and every email your application sends follows the same safe path.
The checklist#
Keep the token on the server#
Read it from a secret store or an environment variable named
EMAIL_API_TOKEN. Use a separate token for each environment.Put the API behind one module#
All email goes through one function such as
sendEmail(message, { key }). Your business code never builds HTTP requests itself, so timeouts, retries and logging live in one place.Send after your own data is saved#
Create the booking, the order or the account first, commit it, then send. An email about something that was rolled back is worse than no email.
Derive the idempotency key from your record#
For example
booking-${id}-confirmation. A retried handler, a double click or a redelivered job then never sends twice.Escape everything users typed#
Names, notes and addresses go into HTML only after escaping. Templates in your own code do this for you if they auto-escape.
Store the message id#
Keep
msg_...next to your record. It lets you check the status and lets the hotel find the message quickly.Decide what happens on failure#
Retry network errors, 429s and 5xx with the same key (the modules below do). For daily limits and final failures, keep the message in your own queue or alert a person.
Client modules#
Each module is self-contained, uses only the language's standard HTTP client (plus requests for Python), sets a 10 second timeout, retries what is safe to retry with the same key, and turns API errors into exceptions that carry code and request_id. Copy it into your project and adapt it as you like; the code samples on this site are free to reuse.
// email-client.mjs: a small client for the Madagascar Email API (Node.js 18+, Deno, Bun, Workers).
const BASE = 'https://email.madagascarhotelags.com';
const RETRYABLE = new Set([429, 500, 502, 503, 504]);
export class EmailApiError extends Error {
constructor(status, problem) {
super(`${problem.code ?? status}: ${problem.detail ?? 'request failed'}`);
this.status = status;
this.code = problem.code;
this.requestId = problem.request_id;
}
}
/**
* Send one message. `key` must be unique per message and stable across retries
* (use your own record id, for example "booking-4821-confirmation").
*/
export async function sendEmail(message, { key, token = process.env.EMAIL_API_TOKEN, attempts = 4 } = {}) {
if (!key) throw new Error('sendEmail needs an idempotency key');
for (let attempt = 1; ; attempt++) {
let res;
try {
res = await fetch(`${BASE}/v1/messages`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
'Idempotency-Key': key,
},
body: JSON.stringify(message),
signal: AbortSignal.timeout(10_000),
});
} catch (networkError) {
if (attempt >= attempts) throw networkError;
await sleep(backoff(attempt));
continue;
}
const body = await res.json().catch(() => ({})); // a proxy error page is not JSON
if (res.ok) return body; // { id, status: 'queued', created_at }
if (!RETRYABLE.has(res.status) || attempt >= attempts) throw new EmailApiError(res.status, body);
const retryAfter = Number(res.headers.get('retry-after'));
// A daily limit resets at midnight UTC: hand the message back to your own queue instead of waiting.
if (retryAfter > 300) throw new EmailApiError(res.status, body);
await sleep(retryAfter > 0 ? retryAfter * 1000 : backoff(attempt));
}
}
export async function getMessage(id, { token = process.env.EMAIL_API_TOKEN } = {}) {
const res = await fetch(`${BASE}/v1/messages/${encodeURIComponent(id)}`, {
headers: { Authorization: `Bearer ${token}` },
signal: AbortSignal.timeout(10_000),
});
const body = await res.json().catch(() => ({}));
if (!res.ok) throw new EmailApiError(res.status, body);
return body;
}
const backoff = (attempt) => Math.min(30_000, 500 * 2 ** attempt) * (0.5 + Math.random() / 2);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));// email-api.d.ts: the shapes the API sends and accepts.
export type Address = string | { email: string; name?: string };
export interface MessageRequest {
to: Address[];
cc?: Address[];
bcc?: Address[];
from?: Address; // one of your token's senders; omitted = the first one
reply_to?: Address;
subject: string; // 1 to 998 characters
html?: string; // at least one of html and text
text?: string;
tags?: string[]; // up to 5 of [A-Za-z0-9_-]{1,32}
scheduled_at?: string; // ISO 8601, 1 minute to 72 hours ahead
}
export type MessageStatus = 'queued' | 'retrying' | 'sent' | 'failed' | 'dead';
export interface Accepted {
id: string; // msg_ followed by 26 characters
status: MessageStatus; // 'queued' for a new message
created_at: string;
}
export interface Message {
id: string;
status: MessageStatus;
from: string;
to: string[];
cc_count: number;
bcc_count: number;
subject: string;
scheduled_at: string | null;
created_at: string;
sent_at: string | null;
attempt: number;
error: string | null; // set when status is failed or dead
delivery: string | null; // reserved: not reported yet
delivery_at: string | null;
suppressed: number; // recipients skipped because they are on the suppression list
}
export interface Problem {
type: string;
title: string;
status: number;
detail: string;
code: string; // stable: switch on this
request_id: string; // quote this when you ask for help
}# email_client.py: a small client for the Madagascar Email API (Python 3.9+, requests).
import os
import random
import time
import requests
BASE = "https://email.madagascarhotelags.com"
RETRYABLE = {429, 500, 502, 503, 504}
class EmailApiError(Exception):
def __init__(self, status, problem):
super().__init__(f"{problem.get('code', status)}: {problem.get('detail', 'request failed')}")
self.status = status
self.code = problem.get("code")
self.request_id = problem.get("request_id")
def _headers(token, key=None):
headers = {"Authorization": f"Bearer {token or os.environ['EMAIL_API_TOKEN']}"}
if key:
headers["Idempotency-Key"] = key
return headers
def send_email(message, key, token=None, attempts=4):
"""Send one message. key must be unique per message and stable across retries."""
for attempt in range(1, attempts + 1):
try:
res = requests.post(f"{BASE}/v1/messages", json=message, headers=_headers(token, key), timeout=10)
except requests.RequestException:
if attempt == attempts:
raise
time.sleep(min(30, 0.5 * 2 ** attempt) * random.uniform(0.5, 1))
continue
try:
body = res.json()
except ValueError: # a proxy error page is not JSON
body = {}
if res.ok:
return body # {"id": ..., "status": "queued", "created_at": ...}
if res.status_code not in RETRYABLE or attempt == attempts:
raise EmailApiError(res.status_code, body)
retry_after = int(res.headers.get("Retry-After", "0") or 0)
if retry_after > 300: # a daily limit: requeue on your side instead of waiting
raise EmailApiError(res.status_code, body)
time.sleep(retry_after or min(30, 0.5 * 2 ** attempt) * random.uniform(0.5, 1))
def get_message(message_id, token=None):
res = requests.get(f"{BASE}/v1/messages/{message_id}", headers=_headers(token), timeout=10)
body = res.json()
if not res.ok:
raise EmailApiError(res.status_code, body)
return body<?php
// EmailClient.php: a small client for the Madagascar Email API (PHP 8.0+, ext-curl).
final class EmailApiException extends RuntimeException
{
public function __construct(public int $status, public array $problem)
{
parent::__construct(($problem['code'] ?? $status) . ': ' . ($problem['detail'] ?? 'request failed'));
}
}
final class EmailClient
{
private const BASE = 'https://email.madagascarhotelags.com';
public function __construct(private string $token) {}
/** Send one message. $key must be unique per message and stable across retries. */
public function send(array $message, string $key, int $attempts = 4): array
{
for ($attempt = 1; ; $attempt++) {
[$status, $body, $retryAfter] = $this->request('POST', '/v1/messages', $message, $key);
if ($status === 202) {
return $body; // ['id' => ..., 'status' => 'queued', 'created_at' => ...]
}
$retryable = in_array($status, [0, 429, 500, 502, 503, 504], true);
if (!$retryable || $attempt >= $attempts || $retryAfter > 300) {
throw new EmailApiException($status, $body);
}
sleep($retryAfter > 0 ? $retryAfter : min(30, 2 ** $attempt));
}
}
public function message(string $id): array
{
[$status, $body] = $this->request('GET', '/v1/messages/' . rawurlencode($id));
if ($status !== 200) {
throw new EmailApiException($status, $body);
}
return $body;
}
private function request(string $method, string $path, ?array $json = null, ?string $key = null): array
{
$retryAfter = 0;
$headers = ['Authorization: Bearer ' . $this->token];
if ($json !== null) {
$headers[] = 'Content-Type: application/json';
}
if ($key !== null) {
$headers[] = 'Idempotency-Key: ' . $key;
}
$ch = curl_init(self::BASE . $path);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$retryAfter) {
if (stripos($line, 'retry-after:') === 0) {
$retryAfter = (int) trim(substr($line, 12));
}
return strlen($line);
},
]);
if ($json !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json));
}
$raw = curl_exec($ch);
$status = $raw === false ? 0 : curl_getinfo($ch, CURLINFO_HTTP_CODE);
return [$status, $raw === false ? ['code' => 'network_error', 'detail' => curl_error($ch)] : (json_decode($raw, true) ?? []), $retryAfter];
}
}// emailapi.go: a small client for the Madagascar Email API (Go 1.21+, standard library only).
package emailapi
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"time"
)
const base = "https://email.madagascarhotelags.com"
var client = &http.Client{Timeout: 10 * time.Second}
type Message struct {
To []string `json:"to"`
Cc []string `json:"cc,omitempty"`
Bcc []string `json:"bcc,omitempty"`
From string `json:"from,omitempty"`
ReplyTo string `json:"reply_to,omitempty"`
Subject string `json:"subject"`
HTML string `json:"html,omitempty"`
Text string `json:"text,omitempty"`
Tags []string `json:"tags,omitempty"`
ScheduledAt string `json:"scheduled_at,omitempty"`
}
type Accepted struct {
ID string `json:"id"`
Status string `json:"status"`
CreatedAt string `json:"created_at"`
}
type Problem struct {
Status int `json:"status"`
Code string `json:"code"`
Detail string `json:"detail"`
RequestID string `json:"request_id"`
}
func (p *Problem) Error() string { return fmt.Sprintf("%s: %s", p.Code, p.Detail) }
// Send posts one message. key must be unique per message and stable across retries.
func Send(m Message, key string) (*Accepted, error) {
body, err := json.Marshal(m)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodPost, base+"/v1/messages", bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("EMAIL_API_TOKEN"))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", key)
res, err := client.Do(req)
if err != nil {
return nil, err // safe to retry with the same key
}
defer res.Body.Close()
if res.StatusCode != http.StatusAccepted {
p := &Problem{}
_ = json.NewDecoder(res.Body).Decode(p)
return nil, p // retry 429 and 5xx after Retry-After, with the same key
}
a := &Accepted{}
return a, json.NewDecoder(res.Body).Decode(a)
}// EmailApi.cs: a small client for the Madagascar Email API (.NET 8+).
using System.Net.Http.Json;
using System.Text.Json.Serialization;
public sealed record EmailMessage(
string[] To,
string Subject,
string? Text = null,
string? Html = null,
string[]? Cc = null,
string[]? Bcc = null,
string? From = null,
[property: JsonPropertyName("reply_to")] string? ReplyTo = null,
string[]? Tags = null,
[property: JsonPropertyName("scheduled_at")] string? ScheduledAt = null);
public sealed record Accepted(string Id, string Status, [property: JsonPropertyName("created_at")] string CreatedAt);
public sealed record Problem(int Status, string Code, string Detail, [property: JsonPropertyName("request_id")] string RequestId);
public sealed class EmailApi(HttpClient http, string token)
{
private static readonly System.Text.Json.JsonSerializerOptions Json = new()
{
PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
/// <summary>Send one message. key must be unique per message and stable across retries.</summary>
public async Task<Accepted> SendAsync(EmailMessage message, string key, CancellationToken ct = default)
{
using var request = new HttpRequestMessage(HttpMethod.Post, "https://email.madagascarhotelags.com/v1/messages")
{
Content = JsonContent.Create(message, options: Json),
};
request.Headers.Authorization = new("Bearer", token);
request.Headers.Add("Idempotency-Key", key);
using var response = await http.SendAsync(request, ct);
if (response.IsSuccessStatusCode)
return (await response.Content.ReadFromJsonAsync<Accepted>(Json, ct))!;
var problem = await response.Content.ReadFromJsonAsync<Problem>(Json, ct);
throw new HttpRequestException($"{problem?.Code}: {problem?.Detail}", null, response.StatusCode);
}
}Using it#
import { sendEmail, EmailApiError } from './email-client.mjs';
try {
const receipt = await sendEmail(
{
to: [booking.email],
subject: 'Your stay is confirmed',
html: renderConfirmationHtml(booking), // your template, auto-escaped
text: renderConfirmationText(booking),
tags: ['booking', 'confirmation'],
},
{ key: `booking-${booking.id}-confirmation` },
);
await db.bookings.update(booking.id, { emailId: receipt.id });
} catch (err) {
if (err instanceof EmailApiError && err.status === 429) await requeueForTomorrow(booking.id);
else throw err;
}from email_client import send_email, EmailApiError
try:
receipt = send_email(
{
"to": [booking.email],
"subject": "Your stay is confirmed",
"html": render_confirmation_html(booking), # your template, auto-escaped
"text": render_confirmation_text(booking),
"tags": ["booking", "confirmation"],
},
key=f"booking-{booking.id}-confirmation",
)
booking.email_id = receipt["id"]
booking.save()
except EmailApiError as err:
if err.status == 429:
requeue_for_tomorrow(booking.id)
else:
raise<?php
$email = new EmailClient(getenv('EMAIL_API_TOKEN'));
$receipt = $email->send([
'to' => [$booking['email']],
'subject' => 'Your stay is confirmed',
'html' => renderConfirmation($booking), // escape with htmlspecialchars()
'text' => 'See you on ' . $booking['check_in'] . '.',
], 'booking-' . $booking['id'] . '-confirmation');
saveEmailId($booking['id'], $receipt['id']);receipt, err := emailapi.Send(emailapi.Message{
To: []string{booking.Email},
Subject: "Your stay is confirmed",
Text: "See you on " + booking.CheckIn + ".",
}, fmt.Sprintf("booking-%d-confirmation", booking.ID))
if err != nil {
return err // a *emailapi.Problem carries Code and RequestID
}
log.Printf("email queued: %s", receipt.ID)var api = new EmailApi(httpClient, Environment.GetEnvironmentVariable("EMAIL_API_TOKEN")!);
var receipt = await api.SendAsync(
new EmailMessage(To: [booking.Email], Subject: "Your stay is confirmed", Text: $"See you on {booking.CheckIn}."),
key: $"booking-{booking.Id}-confirmation");
logger.LogInformation("Email queued {Id}", receipt.Id);Framework notes#
Next.js and other server frameworks#
Call the module from a route handler, server action or background job, never from a client component.
// app/api/bookings/route.ts (Next.js App Router): runs on your server, never in the browser.
import { sendEmail } from '@/lib/email-client.mjs';
export async function POST(request: Request) {
const booking = await saveBooking(await request.json()); // your own code: commit first
// The booking id makes the key unique and stable: a retry of this handler never sends twice.
const receipt = await sendEmail(
{
to: [booking.email],
subject: 'Your stay is confirmed',
text: `See you on ${booking.checkIn}.`,
},
{ key: `booking-${booking.id}-confirmation` },
);
await recordEmailId(booking.id, receipt.id); // keep msg_... with your record
return Response.json({ ok: true });
}Cloudflare Workers#
The Node.js module works unchanged in a Worker (it uses fetch and AbortSignal.timeout). Read the token from env instead of process.env.
// A Cloudflare Worker that sends through the API. Store the token as a secret:
// npx wrangler secret put EMAIL_API_TOKEN
export default {
async fetch(request, env, ctx) {
const order = await request.json();
const res = await fetch('https://email.madagascarhotelags.com/v1/messages', {
method: 'POST',
headers: {
Authorization: `Bearer ${env.EMAIL_API_TOKEN}`,
'Content-Type': 'application/json',
'Idempotency-Key': `order-${order.id}-receipt`,
},
body: JSON.stringify({
to: [order.email],
subject: `Receipt for order ${order.id}`,
text: `Thank you. Your order ${order.id} is confirmed.`,
}),
});
const result = await res.json();
return Response.json(result, { status: res.status });
},
};Background jobs#
Email is a natural fit for a job queue (BullMQ, Celery, Sidekiq, Laravel queues, Cloudflare Queues). Enqueue the job in the same transaction as your record, let the job call the module with the record-derived key, and let the queue's own retry handle crashes: the key keeps every retry safe.
Testing#
- Send your first real messages to an address you own.
- Use a separate token for staging so tests never use production limits. Ask the hotel for one.
- Unit-test your module against recorded responses: a
202, a400withcode, a429withRetry-After, and a network error. - Check the shape of your requests in the request builder without sending anything.
Going live#
- The token is in the production secret store and nowhere else.
GET /v1/mefrom production shows the right name, senders and limits.- Message ids are stored with your records.
- Failures reach a person: logs with
codeandrequest_id, or an alert on failed and dead. - Your expected daily volume fits the token's limits. If not, talk to the hotel first.
Last reviewed 2026-10-01.