# Encore.ts

> Send your first email from an Encore.ts API endpoint using the mailblastr SDK.

[Encore](https://encore.dev) is an open-source TypeScript framework that provisions infrastructure directly from your application code. Use the `mailblastr` Node SDK — install it with `npm install mailblastr` — and read your key from Encore's secrets management.

## Prerequisites

- A MailBlastr [API key](https://www.mailblastr.com/docs/api-keys/overview).
- A [verified domain](https://www.mailblastr.com/docs/domains/managing) to send from.
- Install [Encore](https://encore.dev/docs/ts/install) (`brew install encoredev/tap/encore`).

## 1. Create an Encore app

```bash
encore app create --lang=ts my-app
```

## 2. Install the SDK

```bash
npm install mailblastr
```

## 3. Set your API key

Encore has built-in [secrets management](https://encore.dev/docs/ts/primitives/secrets). Store your MailBlastr API key as a secret — no `.env` files needed.

```bash
encore secret set --type dev,local,pr,production MailBlastrAPIKey
```

## 4. Define a service

Every Encore.ts service needs a service definition file.

**email/encore.service.ts**

```ts
import { Service } from 'encore.dev/service';

export default new Service('email');
```

## 5. Send email from an API endpoint

Create a type-safe API endpoint. Read the secret with `secret()` from `encore.dev/config`, then call `mb.emails.send()`.

**email/send.ts**

```ts
import { api } from 'encore.dev/api';
import { secret } from 'encore.dev/config';
import { MailBlastr } from 'mailblastr';

const mailblastrApiKey = secret('MailBlastrAPIKey');

interface SendRequest {
  to: string;
  subject: string;
  html: string;
}

interface SendResponse {
  id: string;
}

export const sendEmail = api(
  { expose: true, method: 'POST', path: '/email/send' },
  async (req: SendRequest): Promise<SendResponse> => {
    const mb = new MailBlastr(mailblastrApiKey());
    const { data, error } = await mb.emails.send({
      from: 'Acme <onboarding@yourdomain.com>',
      to: req.to,
      subject: req.subject,
      html: req.html,
    });

    if (error) {
      throw new Error(`Failed to send email: ${JSON.stringify(error)}`);
    }

    return { id: data.id };
  },
);
```

## 6. Run the app

```bash
encore run
```

Your API is running at `http://localhost:4000`. Send a test email:

```bash
curl -X POST http://localhost:4000/email/send \
  -H "Content-Type: application/json" \
  -d '{"to":"delivered@example.com","subject":"Hello World","html":"<strong>It works!</strong>"}'
```

> **Note:** See [Send an email](https://www.mailblastr.com/docs/api/emails-send) for every body field, including `cc`, `bcc`, `reply_to`, `tags`, and `scheduled_at`.
