NestJS Transactional Email API (2026): An Injectable Provider That Posts to /emails
Build a NestJS emails module that sends transactional mail through Rovela’s HTTP API: ConfigModule for the Bearer key, a provider around POST /emails, documented scopes, and webhooks for delivery — not a magic-link or cron guide.
A NestJS app should send transactional mail through a provider, not through SMTP
In a NestJS codebase, almost every side effect lives behind an injectable provider. Email should too. A transactional message — a receipt, an “invoice is ready” note, a security alert, a “your export is ready” email — is just another HTTP call your service makes on behalf of a user action.
Rovela’s Email API fits that model directly. There is no official SDK and no @rovela/nestjs package to install. The base URL is https://api.rovela.dev. You send Authorization: Bearer re_… (Authentication) and queue a message with POST /emails. The response is {"object": "email", "id": "..."}. HTTP 200 means accepted and queued, not delivered (Quick Start).
This is not a magic-link tutorial, and it is not a cron job. Sign-in links already have a NestJS guide, and recurring sends belong with @nestjs/schedule or scheduled_at — both covered elsewhere. This article is the everyday provider: an EmailsModule that other feature modules inject, a sending_access key in ConfigModule, an Idempotency-Key on retried work, and a webhook controller for delivery events rather than a polling loop.
If you are choosing a transport, read Email API vs SMTP. Rovela’s SMTP is mailbox SMTP for mail apps: mx.rovela.dev:465, a device credential, send-as-self, 30 messages a minute from one client address. A NestJS process sending customer mail should use POST /emails.
Prerequisites that do not change because you use NestJS
Follow Send your first email once:
- Create an account. The free plan sends real mail. There is no sandbox and no test key.
- Verify a sending domain, often a subdomain such as
mail.example.com. An unverified or foreignfromis a 400 that names the domain. - Create an API key.
sending_accesscan send and nothing else — the right secret for a production provider.full_accesscan also read messages and events and manage domains, templates, and webhooks. The full key is shown once. - Call
POST /emails. - Confirm delivery in the dashboard, with
GET /emails/:idorGET /emails/:id/events(full_accessor a session), or with a webhook.
from is a string such as "Acme <hello@yourdomain.com>" on a verified sending domain. That is the same proof of ownership behind domain email. At least one of html, text, or template is required. Send both html and text when you can (HTML email API).
Never put the key in a NestJS frontend, a public repository, or a browser bundle. A leaked sending_access key can send mail as your domain.
An EmailsModule you can inject anywhere
// emails.service.ts
import { Injectable, HttpException } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
type SendInput = {
to: string;
subject: string;
html: string;
text: string;
idempotencyKey?: string;
replyTo?: string;
};
@Injectable()
export class EmailsService {
private readonly baseUrl = "https://api.rovela.dev";
private readonly apiKey: string;
private readonly from: string;
constructor(config: ConfigService) {
this.apiKey = config.getOrThrow<string>("ROVELA_API_KEY");
this.from = config.get<string>("ROVELA_FROM") ?? "Acme <hello@mail.acme.com>";
}
async send(input: SendInput): Promise<{ object: string; id: string }> {
const headers: Record<string, string> = {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
};
if (input.idempotencyKey) {
headers["Idempotency-Key"] = input.idempotencyKey;
}
const body: Record<string, unknown> = {
from: this.from,
to: input.to,
subject: input.subject,
html: input.html,
text: input.text,
};
if (input.replyTo) body.reply_to = input.replyTo;
const resp = await fetch(`${this.baseUrl}/emails`, {
method: "POST",
headers,
body: JSON.stringify(body),
});
const json = await resp.json();
if (resp.status === 200) return json;
throw new HttpException(json, resp.status);
}
}
// emails.module.ts
import { Global, Module } from "@nestjs/common";
import { EmailsService } from "./emails.service";
@Global()
@Module({
providers: [EmailsService],
exports: [EmailsService],
})
export class EmailsModule {}
Register ConfigModule.forRoot({ isGlobal: true }) and EmailsModule in AppModule. Feature modules then inject EmailsService the same way they inject anything else:
@Injectable()
export class InvoicesService {
constructor(private readonly emails: EmailsService) {}
async emailReady(invoice: { id: string; number: string; customerEmail: string }) {
const result = await this.emails.send({
to: invoice.customerEmail,
subject: `Your invoice ${invoice.number} is ready`,
html: `<p>Invoice ${invoice.number} is ready to view.</p>`,
text: `Invoice ${invoice.number} is ready to view.`,
idempotencyKey: `invoice-${invoice.id}-ready`,
replyTo: "Acme Billing <billing@acme.com>",
});
return result.id;
}
}
The curl form, identical in fields and headers, is:
curl -X POST https://api.rovela.dev/emails \
-H "Authorization: Bearer $ROVELA_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: invoice-10043-ready" \
-d '{
"from": "Acme <hello@mail.acme.com>",
"to": "alice@example.com",
"subject": "Your invoice is ready",
"html": "<p>Invoice 10043 is ready to view.</p>",
"text": "Invoice 10043 is ready to view."
}'
An Idempotency-Key may be up to 256 characters. A retry of the same request within 24 hours returns the original response instead of sending again. Use it anywhere a NestJS queue, Bull/BullMQ worker, or webhook handler might run twice. reply_to is optional and does not replace a verified from (Email API Reply-To). cc and bcc count toward the 50-recipient cap and toward monthly quota, which is charged per recipient (Email API CC and BCC).
You can use fetch, as above, or Nest’s HttpModule. Either way you are calling the documented HTTP API — not an official client.
Errors, scopes, and what the provider should not do
Every error uses the same envelope (Quick Start, Email API error handling):
{
"statusCode": 400,
"name": "Bad Request",
"message": "html or text body is required"
}
Map that onto a NestJS exception filter if you want, but keep the message in your logs:
- 400 — missing required field, unverified or foreign
fromdomain, missing template, attachment base64 that does not decode, or more than 50 recipients acrossto,cc, andbcc. - 401 — missing or invalid key, or a
sending_accesskey used to read, reschedule, or cancel a message. - 429 — rate limit or monthly allowance. Official examples mention
Retry-After. Each entry in a batch counts individually. If the monthly allowance is exhausted, sending stops until the next calendar month unless you upgrade (Pricing).
A 403 on a management endpoint such as GET /domains means the credential is valid but not permitted — typically a sending_access key used for a read. That is expected if your production provider only has sending_access. Give a separate full_access key to the operator tool or webhook debugger that reads GET /emails/:id/events.
The sending provider should not poll for delivery inside the same method that sent the mail. HTTP 200 is not a receipt. Confirm with the dashboard, with GET /emails/:id/events when you are debugging one message (Email delivery status API), or with a webhook in production.
Delivery events belong on a webhook controller, not a cron
For production, subscribe to webhooks and verify the HMAC-SHA256 signature over "<timestamp>.<raw body>" (webhook security). Event types include sent, delivered, delayed, bounced, complained, opened, and clicked. Handle bounces and complaints as documented in the bounces example; do not keep mailing addresses that have already hard-bounced.
A webhook controller is a different NestJS provider from EmailsService. That separation is deliberate. The sending key stays sending_access. The webhook endpoint does not need to call Rovela at all — it verifies the signature with the endpoint’s signing secret and updates your own records. Do not replace this with @nestjs/schedule polling, and do not treat this article as a redo of the Nest schedule cron guide.
POST /emails/batch accepts up to 100 messages, processed independently. template and topic_id are rejected on the batch endpoint; send those through POST /emails. scheduled_at queues a future send; cancelling or rescheduling needs full_access or a dashboard session. Those flows are already covered in the batch and scheduled email guides.
If you prefer stored HTML, use the Templates API. template is mutually exclusive with html and text.
A small exception filter around HttpException is enough to keep controllers from treating every non-200 as a generic 500. If the body already has statusCode, name, and message, return those fields to your own logs and, when the caller is an internal operator tool, to the API response. Do not rewrite the message into something vaguer — the documented message is meant to be surfaced as-is, for example when it names an unverified domain.
When you write unit tests for InvoicesService, stub EmailsService.send rather than hitting the live API from a unit test. When you do a live rehearsal, you are sending real mail: use a verified staging domain, recipients you control, and a stable idempotency key so repeated test runs do not multiply messages. The official events on a full_access key, or the dashboard Emails view, are how you confirm a rehearsal actually arrived.
What not to bolt onto the module
Do not add Nodemailer, or any SMTP transport, and point it at mx.rovela.dev for application volume. Mailbox SMTP is for webmail and mail apps, send-as-self, 30 messages a minute, without the HTTP API’s tracking, logs, or webhooks (SMTP, Email API vs SMTP relay, and the Nodemailer alternative if you are migrating a Node SMTP client).
Do not invent official SDK methods, a sandbox flag, dedicated IPs, numeric HTTP rate (req/s) figures, or a /logs endpoint. Delivery history is in the dashboard and on the documented events API.
If one NestJS organization sends for several customer domains, restrict each key to a single domain so a leaked key cannot send as somebody else (Authentication, Email API for multi-tenant SaaS).
During development there is still no test mode. Use a verified staging subdomain and recipients you control (test a transactional email API).
A NestJS checklist
- Verify the sending domain used in
from. - Load a
sending_accesskey through ConfigModule. Keep it on the server. - Export one
EmailsServicethat callsPOST /emailswith the documented fields. - Send both
htmlandtext. Setreply_towhen a human should be able to answer. - Pass an
Idempotency-Keyfrom queues, workers, and webhook-driven sends. - Handle 400, 401, and 429 from the documented envelope. Treat 200 as queued.
- Confirm delivery on a signature-verified webhook, not by polling from the sender.
- Leave mailbox SMTP to people and mail apps.
Once the module exists, invoices, security alerts, and “your export is ready” notes are all the same injection. That is what a NestJS transactional email API integration should look like: one provider, documented HTTP, no second mail stack.