2

I'm using nest-modules/mailer to send an email and I have some trouble during the config setup for MailerModule.

(1) Previously I was using a raw dotenv package to my config in main.ts like:

dotenv.config({
  path: 'src/config/config.env',
});
    

But I can't assign the config to MailerModule in app.module.ts.

(2) Then I tried to setup config using @nesjs/config and the app.module.ts looks like this:

import config from 'src/config/config';

@Module({
  controllers: [
    //...
  ],
  providers: [
   //...
 ],
  imports: [
    HttpModule,
    ConfigModule.forRoot({
      load: [config]
    }),
    MailerModule.forRoot({
      transport: {
        ignoreTLS: true,
        secure: false, // true for 465, false for other ports
        host: process.env.EMAIL_HOST,
        port: process.env.EMAIL_PORT,
        auth: {
          user: process.env.EMAILDEV_INCOMING_USER,
          pass: process.env.EMAILDEV_INCOMING_PWD 
        },
      },
      defaults: {
        from: `'nest-modules' ${process.env.EMAILDEV_INCOMING_}`, // outgoing email ID
      },
      template: {
     
      },
    })
  ]
})
export class AppModule implements NestModule {
 //...
}

So there's no way I can use configService and process.env.* to load the config for MailerModule.

How should I fix this?

Arnold Schrijver
  • 3,588
  • 3
  • 36
  • 65
Zchary
  • 968
  • 7
  • 14

2 Answers2

2

I figured out how to solve this properly at the current stage:

load the EmailModule asynchronously (and others you need to use configs).

imports: [
    HttpModule,
    MailerModule.forRootAsync({
      useFactory: async () => {
        return {
          transport: {
            ignoreTLS: true,
            secure: false, // true for 465, false for other ports
            host: process.env.EMAIL_HOST,
            port: process.env.EMAIL_PORT,
            auth: {
              user: process.env.EMAILDEV_INCOMING_USER, // generated ethereal user
              pass: process.env.EMAILDEV_INCOMING_PWD // generated ethereal password
            },
          },
          defaults: {
            from: `'nest-modules' ${process.env.EMAILDEV_INCOMING_}`, // outgoing email ID
          },
          template: {
            dir: process.cwd() + '/src/shared/static/views',
            adapter: new HandlebarsAdapter(),
            options: {
              strict: true,
            },
          },
        }
      }
    })
  ]
Zchary
  • 968
  • 7
  • 14
0

Looking at the sample code provided with nest-modules/mailer it is enough to load your .env like this in AppModule, directly from dotenv with a require import:

require('dotenv').config({
  path: 'src/config/config.env',
});

And you can probably also use a typescript import of dotenv and call config() in a line above your AppModule definition or, better, in your main.ts bootstrap() function before you instantiate the NestJS app.

Arnold Schrijver
  • 3,588
  • 3
  • 36
  • 65