This is a simple NestJS mailer module based on NodeMailer.
This package is meant to be a wrapper of NodeMailer (nothing less, nothing more). If your goal is to be able to use NodeMailer within NestJS then this package is for you.
IMPORTANT: This package will never add native support for template engines (such as pug, handlebars, etc...).
Installation is as simple as running:
npm install @enricoemiro/mailer nodemailer
npm install --save-dev @types/nodemailer
# OR
yarn add @enricoemiro/mailer nodemailer
yarn add -D @types/nodemailer
A basic usage example:
- Register the module as a dependency (
app.module.ts
)
Using forRoot()
import { MailerModule } from '@enricoemiro/mailer';
MailerModule.forRoot({
transports: [
{
name: 'mailtrap',
transport: {
host: 'smtp.mailtrap.io',
// ... transport settings
},
},
],
isGlobal: true,
});
Using forRootAsync()
- Using
useFactory
import { MailerModule } from '@enricoemiro/mailer';
MailerModule.forRootAsync({
imports: [ConfigModule],
useFactory: async function (configService: ConfigService) {
return {
transports: [
{
name: 'mailtrap',
transport: {
host: configService.get<string>('MAIL_HOST'),
// ... transport settings
},
},
];
};
},
inject: [ConfigService],
isGlobal: true,
});
- Using
useClass
oruseExisting
@Injectable()
export class MailerConfigService implements MailerTransportFactory {
createMailerModuleOptions(): Promise<MailerModuleOptions> | MailerModuleOptions {
return {
transports: [
{
name: 'smtp',
transport: {
// ... transport settings
},
},
];
};
}
}
import { MailerModule } from '@enricoemiro/mailer';
import { MailerConfigService } from './mailerConfigServicePath.ts';
MailerModule.forRootAsync({
useClass: MailerConfigService,
isGlobal: true,
});
- Inject the
MailerService
as a dependency:
import { MailerService } from '@enricoemiro/mailer';
@Injectable()
export class YourService {
constructor(private mailerService: MailerService) {}
async sendHelloWorldEmail() {
this.mailerService.sendAsyncMail('mailtrap', {
from: '"Ghost Foo 👻" <foo@example.com>',
to: 'bar@example.com, baz@example.com',
subject: 'Hello ✔',
text: 'Hello world?',
html: '<b>Hello world?</b>',
});
}
}
The MailerModule
can be instantied synchronously or asynchronously using respectively:
forRoot(options: MailerModuleOptions)
forRootAsync(options: MailerModuleAsyncOptions)
The MailerService
exposes the following two methods:
sendAsyncEmail(name: string, mailOptions: Mail.Options): Promise<SentMessageInfo>
getTransporter(name: string): Transporter
All changelog are available here.
MIT