I have the next configuration for nodemailer package:
//App module
@Module({
imports: [
MailerModule.forRoot({
transport: {
host: 'localhost',
port: 3000,
secure: false,
},
defaults: {
from: '"nest-modules" <modules@nestjs.com>',
},
template: {
dir: __dirname + '/templates',
adapter: new HandlebarsAdapter(),
options: {
strict: true,
},
},
}),
...
})
export class AppModule {}
And
//Email service
export class EmailService {
constructor(private readonly mailerService: MailerService) {}
public example(): void {
this.mailerService
.sendMail({
to: 'email@gmail.com', // list of receivers
from: 'test@nestjs.com', // sender address
subject: 'Testing Nest MailerModule ✔', // Subject line
text: 'welcome', // plaintext body
html: '<b>welcome</b>', // HTML body content
})
.then((r) => {
console.log(r, 'email is sent');
})
.catch((e) => {
console.log(e, 'error sending email');
});
}
}
I am using my local environement. Tring the code above i get an error in catch block: Error: Greeting never received. Why i get that error and how to send the email without any issue?
MailerModule.forRoot({
transport: {
host: 'localhost',
port: 3000,
secure: false,
},
nodemailer try to find SMTP mail transfer agent (relay) listening on localhost:3000. Its unlikely there is SMTP server on your machine on 3000 port, so most likely nodemailer cannot receive confirmation from anything on your 3000 port that it is SMTP server and throws error you mentioned.
Code will be something like this:
import {directTransport} from 'nodemailer-direct-transport';
//App module
@Module({
imports: [
MailerModule.forRoot({
transport: directTransport({}),
defaults: {
from: '"nest-modules" <modules@nestjs.com>',
},
template: {
dir: __dirname + '/templates',
adapter: new HandlebarsAdapter(),
options: {
strict: true,
},
},
}),
...
})
export class AppModule {}
I'm not sure if you just wanna send an email using local SMTP or send an email in any SMTP available
if it's the latter you can use google SMTP or mailtrap.No need to set up SMTP server. The configuration will be
MailerModule.forRoot({
transport: {
host: "smtp.gmail.com",
port: "465",
secure: true,
auth: {
user: "your_gmail_email",
pass: "your_gmail_app_password"
}
}
})
// or for mailtrap.io
const nodemailer = require('nodemailer');
let transporter = nodemailer.createTransport({
host: 'smtp.mailtrap.io',
port: 2525,
auth: {
user: "<user>",
pass: "<pass>"
}
})
In the case of a local SMTP server, you can check smtp-server to create an SMTP server or MaiDev will help you to set up an SMTP server locally. MailDev has also available via docker that would be easier too.