# Send email from NestJS

A `MailService` provider holds the client, a controller sends through it, and the webhook controller verifies `req.rawBody`. Nest keeps that raw body only when the app is created with `rawBody: true`.

## Install the TypeScript SDK

`mailset` from npm, pnpm, Bun or Yarn, next to `@nestjs/common`. Its types ship inside the package, so the client type-checks with your decorators and DTOs.

npm:

```bash
npm install mailset
```

pnpm:

```bash
pnpm add mailset
```

bun:

```bash
bun add mailset
```

yarn:

```bash
yarn add mailset
```

## Send your first email from NestJS

`MailService` is `@Injectable()`, so Nest makes one for the app, and its client reads `MAILSET_KEY`. `CodesController` takes the service in its constructor and calls `sendCode` with the posted email; `deliverBy: '10m'` refuses a code that would come late, and the route answers the receipt’s `id`.

```typescript
import {
	Body,
	Controller,
	// A provider: Nest makes one for the app.
	Injectable,
	Module,
	Post,
} from '@nestjs/common';
import { Mailset } from 'mailset';

@Injectable()
export class MailService {
	// One client for the app. Reads MAILSET_KEY.
	private readonly mailset = new Mailset();

	sendCode(email: string) {
		return this.mailset.send({
			from: 'Acme <hello@example.com>',
			to: email,
			subject: 'Your Acme code',
			text: 'Your code is 123456.',
			deliverBy: '10m',
		});
	}
}

@Controller('codes')
export class CodesController {
	constructor(private readonly mail: MailService) {}

	@Post()
	async send(@Body('email') email: string) {
		const sent = await this.mail.sendCode(email);
		return { id: sent.id };
	}
}

@Module({
	controllers: [CodesController],
	providers: [MailService],
})
export class AppModule {}
```

## Verify webhooks from req.rawBody

`EventsController` reads `req.rawBody` through `RawBodyRequest<Request>`, since `@Body()` would be parsed JSON. `bootstrap` creates the app with `rawBody: true`, without which `req.rawBody` is undefined. A failed check throws `UnauthorizedException` with the error’s code, and `@HttpCode(204)` answers a batch that went through.

```typescript
import {
	Controller,
	HttpCode,
	Module,
	Post,
	type RawBodyRequest,
	Req,
	UnauthorizedException,
} from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import type { Request } from 'express';
import { MailsetError, webhooks } from 'mailset';

const secret = process.env.MAILSET_HOOK_SECRET ?? '';

@Controller('mailset')
export class EventsController {
	@Post('events')
	@HttpCode(204)
	async events(@Req() req: RawBodyRequest<Request>) {
		// The signature covers the body as it came: verify
		// req.rawBody: @Body() is parsed JSON, not the bytes.
		try {
			const events = await webhooks.verify({
				body: req.rawBody ?? '',
				headers: req.headers,
				secret,
			});
			for (const event of events) {
				if (event.type !== 'bounced') continue;
				if (event.bounce.kind === 'hard')
					console.log('Stop writing to', event.recipient);
			}
		} catch (error) {
			if (!(error instanceof MailsetError)) throw error;
			throw new UnauthorizedException(error.code);
		}
	}
}

@Module({ controllers: [EventsController] })
export class AppModule {}

export async function bootstrap() {
	// Without rawBody: true, req.rawBody is undefined.
	const app = await NestFactory.create(AppModule, {
		rawBody: true,
	});
	await app.listen(process.env.PORT ?? 3000);
	return app;
}
```

In the SDK’s tests: run on NestJS 11, type-checked by tsc.

## Send from your own domain

Your product sends as your own domain either way. What changes is where your team’s mail lives.

- **Sending only.** Your team’s mail stays at Google, Microsoft or wherever it is now. Mailset asks for DKIM, a bounce host and DMARC, and leaves your MX alone. [Send from a domain whose mail stays elsewhere](https://mailset.app/docs/recipes/sending-only)
- **Mailboxes too.** Your team’s mail moves to Mailset, with a real mailbox for every address on the domain and your product’s email on the same bill. [Set up a domain](https://mailset.app/guide/onboarding)

```bash
mailset domains add example.com --sending
mailset domains apply example.com --sending
mailset domains check example.com
mailset keys create --send --domain example.com --from hello@example.com --name "Acme API"
```

## What the TypeScript SDK’s build checks

Each line comes from the SDK’s own build, which fails when one stops being true.

- **Node.js 20+**: Tested: a real send runs on it (a test)
- **Bun 1.4+**: Tested: a real send runs on it (a test)
- **Deno 2.9+**: Tested: a real send runs on it (a test)
- **Cloudflare Workers**: Compatibility date 2024-01-01, tested (a test)
- **No dependencies**: Nothing else to install beside it (its manifest)
- **Typed throughout**: Types for every command and answer (a test)
- **30 KB**: The whole SDK, minified, as one ES module (the build)

## Where to go from here

- [The TypeScript SDK](https://mailset.app/docs/sdk/typescript): Every task, from the client’s options to errors and retries.
- [Send email from Node.js](https://mailset.app/send-email/nodejs): The TypeScript guide, with no framework around it.
- [Webhooks](https://mailset.app/docs/webhooks): The events Mailset posts about your product’s email, and how to check a request’s signature.
- [Give sign-in codes a deadline](https://mailset.app/docs/recipes/deadlines): Use deliverBy so a code that would arrive late is never sent.
- [Retry without sending twice](https://mailset.app/docs/recipes/retries): Make a send safe to repeat with an idempotency key or a Message-ID.
- [Handle bounces](https://mailset.app/docs/recipes/bounces): Tell a dead address from a full inbox, and keep your list clean.
- [Send many messages at once](https://mailset.app/docs/recipes/batches): Up to 100 messages a request, each with its own answer.

## Product email on every plan

Both include 10,000 emails a month, your product’s and your team’s together. Past that it’s $0.40 per 1,000 with pay as you go. Every plan and price: https://mailset.app/pricing

## Sending from NestJS, asked and answered

### Why rawBody: true?

Nest parses JSON bodies before a controller runs. With `rawBody: true` in `NestFactory.create`, it also keeps the bytes as `req.rawBody`, which is what the signature covers.

### Why not @Body() for the webhook?

`@Body()` hands over the parsed object, and the bytes it came from are gone. Verify `req.rawBody` instead; `webhooks.verify` returns the events typed.

### Should the client be a provider?

Yes. As an `@Injectable()` service it is made once and injected wherever a controller or another provider asks for it.

### What does a bad signature get back?

`UnauthorizedException(error.code)` makes Nest answer 401 with the reason. Mailset posts that batch again later, so a fixed secret catches up.

## Try it on your own domain

7 days free, with everything on. Make a key, run the example above and watch the receipt come back. Start at https://mailset.app/start

---

© 2026 Intenseloop, Inc. Mailset’s site, docs and guides are copyrighted. You may read them and use their code to build with Mailset. Don’t republish them or use them to build a copy of Mailset. Terms: https://mailset.app/terms#content