Send with

Send email with Bun

Bun has fetch built in and loads .env files automatically.

Setup

# .env
ROBUSTEMAIL_API_KEY=rb_test_...

Send an email

// email.ts
const API = "https://robustemail.com/api/v2/emails";

export async function sendEmail(email: Record<string, unknown>, idempotencyKey?: string): Promise<string> {
  const res = await fetch(API, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${Bun.env.ROBUSTEMAIL_API_KEY}`,
      "Content-Type": "application/json",
      ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
    },
    body: JSON.stringify(email),
  });

  const body = await res.json();
  if (!res.ok) {
    throw new Error(`${body.name}: ${body.message}`);
  }
  return body.id;
}
// send.ts
import { sendEmail } from "./email";

const id = await sendEmail({
  from: "Acme <hello@acme.com>",
  to: "delivered@sandbox.robustemail.dev",
  subject: "Welcome to Acme",
  html: "<h1>Welcome!</h1><p>Thanks for signing up.</p>",
}, "welcome-user-1042");

console.log("Queued", id);

Run it with bun send.ts.

From a Bun server

// server.ts
import { sendEmail } from "./email";

Bun.serve({
  port: 3000,
  async fetch(req) {
    const url = new URL(req.url);
    if (req.method === "POST" && url.pathname === "/contact") {
      const { email, message } = await req.json();
      await sendEmail({
        from: "Acme Website <website@acme.com>",
        to: "team@acme.com",
        reply_to: email,
        subject: "New contact form message",
        text: String(message),
      });
      return Response.json({ ok: true });
    }
    return new Response("Not found", { status: 404 });
  },
});

Send contact form messages from your own domain and put the visitor’s address in reply_to. Sending “from” the visitor’s address would fail authentication.

Attach a file

const pdf = Buffer.from(await Bun.file("invoice-2041.pdf").arrayBuffer()).toString("base64");
// attachments: [{ filename: "invoice-2041.pdf", content: pdf, content_type: "application/pdf" }]

Next