Send email from Supabase Edge Functions with Shipmail
Send a welcome email from an Edge Function each time a row lands in your profiles table. The function calls the Shipmail API with fetch, so it needs no package.
Last updated
Before you start
- A verified sending subdomain, such as
notify.example.com, with an active sender. See Transactional email. - An API key with send access to the sender's mailbox.
- The sender address, such as
hello@notify.example.com. Use the bare address. Shipmail adds the sender name.
Store the key as a secret
Create the function, then set the key and the sender address as secrets. Edge Functions read them with Deno.env.get().
supabase functions new send-welcome-emailsupabase secrets set SHIPMAIL_API_KEY=sm_live_...
supabase secrets set EMAIL_FROM=hello@notify.example.comWrite the function
The idempotency key is built from the row id, so Shipmail sends one welcome email per row even if the function runs twice within 24 hours. On a 429, the function waits for the number of seconds in Retry-After and tries again, up to three times. See Idempotency and Rate limits.
// supabase/functions/send-welcome-email/index.ts
async function sendEmail(body: object, idempotencyKey: string) {
for (let attempt = 1; ; attempt++) {
const res = await fetch("https://shipmail.to/api/v1/messages", {
method: "POST",
headers: {
Authorization: `Bearer ${Deno.env.get("SHIPMAIL_API_KEY")}`,
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey,
},
body: JSON.stringify(body),
});
if (res.status !== 429 || attempt === 3) return res;
const wait = Number(res.headers.get("Retry-After") ?? 1);
await new Promise((resolve) => setTimeout(resolve, wait * 1000));
}
}
Deno.serve(async (req) => {
const { record } = await req.json();
const res = await sendEmail(
{
from: Deno.env.get("EMAIL_FROM"),
to: [record.email],
subject: "Welcome to Acme",
text: "Thanks for signing up.",
},
`welcome-${record.id}`,
);
if (!res.ok) {
console.error(`Shipmail returned ${res.status}: ${await res.text()}`);
return Response.json({ error: "Email not sent" }, { status: 502 });
}
return Response.json(await res.json());
});Deploy and trigger it
supabase functions deploy send-welcome-emailIn the Supabase dashboard, add a Database Webhook for Insert events on profiles and point it at the send-welcome-email function. The webhook posts the new row as record.
Test without sending
Use a sm_test_ key while you build. Shipmail accepts the request, delivers nothing and lists the send under Test in Activity. See Sandbox mode. To run the function on your machine, put the test key in a local env file. The CLI reads it when it serves the function.
# supabase/functions/.env
SHIPMAIL_API_KEY=sm_test_...
EMAIL_FROM=hello@notify.example.comsupabase functions serve