I'm trying to connect nodemailer to send mails to users after registration. So I turned on IMAP in google settings, than I created app to generate password, and it all works with this serivs. But when I try to connect mail service, I have this error
Error: connect ECONNREFUSED 127.0.0.1:587 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16) { errno: -111, code: 'ESOCKET', syscall: 'connect', address: '127.0.0.1', port: 587, command: 'CONN' }
mail-service:
import nodemailer from "nodemailer";
class MailService {
constructor() {
this.transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
secure: false,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASSWORD,
},
});
}
async sendActicvationMail(to, link) {
await this.transporter.sendMail({
from: process.env.SMTP_USER,
to,
subject: "Mail activation " + process.env.API_URl,
text: "",
html: `
<div>
<h1>For activation click on link</h1>
<a href="${link}">Click here !</a>
</div>
`,
});
}
}
export default new MailService();
Where I might made mistake ? Thank you !
I had the same problem and used the dotenv configuration in this file.
import nodemailer from "nodemailer";
// dotenv must be used
import dotenv from "dotenv";
dotenv.config();
// dotenv
class MailService {
constructor() {
this.transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: parseInt(process.env.SMTP_PORT, 10),
secure: false,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASSWORD,
},
});
}
async sendMail(email, activationLink) {
await this.transporter.sendMail({
from: process.env.SMTP_USER,
to: email,
subject: `Activation account link ${activationLink}`,
html: `
<div>
<a href="${activationLink}">Click to activate account</a>
</div>
`,
});
}
}
export default new MailService();