I was using @nestjs-modules/mailer
in my NestJS API to send emails. As a part of abstraction, common functions and services that are being used by multiple APIs are abstracted out and published as libraries in GitHub.
While doing the same with @nestjs-modules/mailer
I am getting this error.
Error setting up transport: Cannot read properties of undefined (reading 'addTransporter')
Here is my module:
@Module({})
export class EmailModule {
static forRoot(options: EmailModuleOptions): DynamicModule {
const emailOptionsProvider: Provider = {
provide: 'EMAIL_MODULE_OPTIONS',
useValue: options,
};
return {
module: EmailModule,
imports: [
MailerModule.forRoot({
transport: 'smtps://[email protected]:[email protected]',
template: {
dir: path.join(__dirname, 'templates'),
adapter: new HandlebarsAdapter(),
options: {
strict: true,
},
},
}),
],
providers: [emailOptionsProvider, EmailService],
exports: [EmailService],
global: true,
};
}
}
Here is my service:
@Injectable()
export class EmailService {
email;
emailPassword;
constructor(
@Inject('EMAIL_MODULE_OPTIONS') private options: EmailModuleOptions,
private readonly mailerService: MailerService,
) {
this.email = options.adminEmail;
this.emailPassword = options.adminEmailPassword;
}
async sendEmail(action, to, subject, context) {
context.year = new Date().getFullYear();
const from = this.email;
try {
await this.setAdminTransport();
await this.mailerService.sendMail({
transporterName: 'zoho',
to,
from,
subject,
template: action,
context,
});
} catch (error) {
console.error('Error sending mail:', error.message);
}
}
private async setAdminTransport(): Promise<void> {
try {
const config: Options = {
host: 'smtp.zoho.au',
port: 465,
secure: true,
auth: {
user: this.email,
pass: this.emailPassword,
},
};
this.mailerService.addTransporter('zoho', config); // here is the error.
} catch (error) {
console.error('Error setting up transport:', error.message);
throw error;
}
}
}
I am not providing the transport in the Module as I have multiple transports and I need them to be set accordingly (I have removed that code from above).
The above code is published as a package in GitHub and is being used in my API.
In my API, I am importing this module in app.module
to provide the email address and password and then injecting the new EmailService
to call sendEmail
The MailerService
is not being injected. How can I inject that?