Injectable MailService in NestJS
Wrap Publiq in an injectable provider and send emails from any NestJS service or controller.
Create the MailService, register it in the module providers and inject it wherever needed:
import { Injectable } from '@nestjs/common';
import { Publiq } from 'publiq';
@Injectable()
export class MailService {
private readonly publiq = new Publiq(process.env.PUBLIQ_API_KEY);
sendWelcome(to: string, firstName: string) {
return this.publiq.emails.send({
from: 'you@yourdomain.com',
to,
templateKey: 'welcome-email',
variables: { first_name: firstName },
});
}
}Best practices
- Always call Publiq from the server — never expose the API key on the client.
- Create the client instance once and reuse it across requests.
- Prefer
templateKeyover inline HTML to keep content versioned. - Handle
PubliqError(status/code); the SDK already retries transient errors with backoff. - Send from a verified domain — see Domains.