콘텐츠로 이동

Bun

  1. SDK를 설치합니다.

    터미널 창
    bun add @spacepost/node
  2. 키를 .env에 넣습니다. Bun이 자동으로 불러옵니다.

    .env
    SPACEPOST_API_KEY=sp_live_YOUR_API_KEY
  3. 이메일을 보냅니다.

    send.ts
    import { SpacePost } from "@spacepost/node";
    const spacepost = new SpacePost(Bun.env.SPACEPOST_API_KEY);
    const { data, error } = await spacepost.emails.send({
    from: "Acme <hello@acme.com>",
    to: "user@example.com",
    subject: "Hello from Bun",
    html: "<p>Sent with Bun and SpacePost.</p>",
    });
    console.log(error ?? data);
    터미널 창
    bun run send.ts

요청이 오면 메일을 보내는 간단한 HTTP 서버입니다.

server.ts
import { SpacePost } from "@spacepost/node";
const spacepost = new SpacePost();
Bun.serve({
port: 3000,
async fetch(req) {
if (req.method !== "POST") return new Response("POST only", { status: 405 });
const { email } = (await req.json()) as { email: string };
const { data, error } = await spacepost.emails.send(
{ from: "Acme <hello@acme.com>", to: email, subject: "Thanks for signing up", text: "We will be in touch." },
{ idempotencyKey: `signup-${email}` },
);
return Response.json(error ?? data, { status: error?.statusCode ?? 200 });
},
});