Send with

Send email with Deno

Deno has fetch built in. Grant only the permissions the script needs: network access and the one environment variable.

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 ${Deno.env.get("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;
}

if (import.meta.main) {
  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);
}
ROBUSTEMAIL_API_KEY=rb_test_... \
  deno run --allow-net=robustemail.com --allow-env=ROBUSTEMAIL_API_KEY email.ts

From a server

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

Deno.serve(async (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 });
});

A server also needs permission to listen, so run it with --allow-net (or list both the port and the API host).

Attach a file

import { encodeBase64 } from "jsr:@std/encoding/base64";

const pdf = encodeBase64(await Deno.readFile("invoice-2041.pdf")); // needs --allow-read
// attachments: [{ filename: "invoice-2041.pdf", content: pdf, content_type: "application/pdf" }]

Next