unsent
unsent.dev
Guides

TanStack Start

How to send emails with Unsent in TanStack Start

Introduction

This guide shows how to send emails using Unsent in a TanStack Start application using Server Functions.

Install dependencies

npm install @unsent/sdk
pnpm add @unsent/sdk
yarn add @unsent/sdk
bun add @unsent/sdk

Configure API Key

Add your Unsent API key to your environment variables file (.env).

.env
UNSENT_API_KEY=un_...

Create Server Function

Create a server function to send emails.

app/functions/send-email.ts
import { createServerFn } from '@tanstack/start';
import { Unsent } from '@unsent/sdk';

const unsent = new Unsent(process.env.UNSENT_API_KEY);

export const sendEmail = createServerFn('POST', async (payload: { email: string }) => {
  const { data, error } = await unsent.emails.send({
    from: 'Acme <onboarding@unsent.dev>',
    to: [payload.email],
    subject: 'Hello world',
    html: '<strong>It works!</strong>',
  });

  if (error) {
    throw new Error(error.message);
  }

  return data;
});

Use in Component

Call the server function from your component.

app/routes/index.tsx
import { sendEmail } from '../functions/send-email';

export default function Home() {
  return (
    <button
      onClick={async () => {
        await sendEmail({ email: 'delivered@unsent.dev' });
        alert('Email sent!');
      }}
    >
      Send Email
    </button>
  );
}