Functional Weave
Code in Rust

email.send@1.0.0

adapters/typescript/resend.ts

1,755 bytes · the TypeScript implementation · view raw

import { io, requireEnv } from "./funeio.ts";
import type { EmailMessage, SentEmail } from "./email_send_types.ts";

const ENDPOINT = "https://api.resend.com/emails";

/**
 * Resend's HTTP API: one POST per message. A refusal is thrown with the
 * status and Resend's own message, which says what to fix.
 */
export async function sendWithResend(message: EmailMessage, from: string): Promise<SentEmail> {
  const key = requireEnv("RESEND_API_KEY");
  const body: Record<string, unknown> = { from, to: message.to, subject: message.subject };
  if (message.text) body.text = message.text;
  if (message.html) body.html = message.html;
  if (message.cc?.length) body.cc = message.cc;
  if (message.bcc?.length) body.bcc = message.bcc;
  if (message.replyTo) body.reply_to = message.replyTo;
  const res = await io().http({
    method: "POST",
    url: ENDPOINT,
    headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
    body: JSON.stringify(body),
  });
  let parsed: { id?: unknown; message?: unknown; name?: unknown } = {};
  try {
    parsed = JSON.parse(res.body);
  } catch {
    parsed = {};
  }
  if (res.status === 401 || res.status === 403) {
    throw new Error(`resend refused RESEND_API_KEY (${res.status}): ${String(parsed.message ?? "unauthorised")}`);
  }
  if (res.status === 429) throw new Error("resend is rate limiting this key (429); try again shortly");
  if (res.status < 200 || res.status > 299) {
    throw new Error(`resend refused the email (${res.status}${parsed.name ? ` ${String(parsed.name)}` : ""}): ${String(parsed.message ?? res.body)}`);
  }
  if (typeof parsed.id !== "string") throw new Error(`resend answered ${res.status} without an id`);
  return { provider: "resend", id: parsed.id };
}