/nestjs-nodemailer

Nest Node Mailer with updated node mailer version

Primary LanguageTypeScript

Nest Logo

A progressive Node.js framework for building efficient and scalable server-side applications, heavily inspired by Angular.

NPM Version Package License NPM Downloads Travis Linux Coverage Gitter Backers on Open Collective Sponsors on Open Collective

Description

Nodemailer utilities module for Nest based on the nodemailer package.

Installation

$ npm i --save @iaminfinity/nodemailer

Usage

Import NodemailerModule:

@Module({
  imports: [
    NodemailerModule.register({
      host: 'smtp.example.com',
      port: 587,
      secure: false,
      auth: {
          user: 'username',
          pass: 'password'
      }
    })
  ],
  providers: [...]
})
export class AppModule {}

Inject NodemailerService:

@Injectable()
export class AppService {
  constructor(private readonly nodemailerService: NodemailerService) {}
}

Async options

Quite often you might want to asynchronously pass your module options instead of passing them beforehand. In such case, use registerAsync() method, that provides a couple of various ways to deal with async data.

1. Use factory

NodemailerModule.registerAsync({
  useFactory: () => ({
    host: 'smtp.example.com',
    port: 587,
    secure: false,
    auth: {
        user: 'username',
        pass: 'password'
    }
  })
})

Obviously, our factory behaves like every other one (might be async and is able to inject dependencies through inject).

NodemailerModule.registerAsync({
  imports: [ConfigModule],
  useFactory: async (configService: ConfigService) => configService.getMailConfig(),
  inject: [ConfigService],
})

2. Use class

NodemailerModule.registerAsync({
  useClass: NodemailerConfigService
})

Above construction will instantiate JwtConfigService inside JwtModule and will leverage it to create options objec

class NodemailerConfigService implements NodemailerOptionsFactory {
  createNodemailerOptions(): NodemailerModuleOptions {
    return {
      host: 'smtp.example.com',
      port: 587,
      secure: false,
      auth: {
        user: 'username',
        pass: 'password'
      }
    };
  }
}

3. Use existing

NodemailerModule.registerAsync({
  imports: [ConfigModule],
  useExisting: ConfigService
})

It works the same as useClass with one critical difference - NodemailerModule will lookup imported modules to reuse already created ConfigService, instead of instantiating it on its own.

Stay in touch