I’m trying to setup a transporter in the NestJS lifecylce method onModuleInit()
with the npm library “Nodemailer”. So that I can easily send emails from other services in my backend, but I’m getting an error that says the get
method is undefined on configService
. Bear in mind I can successfully retrieve my environment variables from other methods within my MailService
class, it’s just the onModuleInit()
that’s cause for grief. Is there some OOP principle that I’m not privy to which is my cause for issue? Any help appreciated, thanks in advance!
CODE
import { OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as nodemailer from 'nodemailer';
import SMTPTransport from 'nodemailer/lib/smtp-transport';
interface EnvironmentVariables {
MAIL_USER: string;
MAIL_PASS: string;
}
export class MailService implements OnModuleInit {
transporter: nodemailer.Transporter<SMTPTransport.SentMessageInfo>;
constructor(private configService: ConfigService<EnvironmentVariables>) {}
onModuleInit() {
this.transporter = nodemailer.createTransport(
{
host: 'smtp.office365.com',
secure: false,
tls: {
ciphers: 'SSLv3',
},
auth: {
user: this.configService.get('MAIL_USER', { infer: true }),
pass: this.configService.get('MAIL_PASS', { infer: true }),
},
logger: true,
allowInternalNetworkInterfaces: false,
})
}
ERROR
user: this.configService.get('MAIL_USER', { infer: true }),
^
TypeError: Cannot read properties of undefined (reading 'get')
I was able to successfully retrieve environment variables with the get
method in other methods that I had defined within the MailService
class that I had created.