Search code examples
node.jsexpresssmtpnodemailer

Error: connect ECONNREFUSED 127.0.0.1:587 nodemailer NodeJS


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 !


Solution

  • Daniil

    This code is working for me. But I configured "Sign in using app passwords" https://support.google.com/mail/answer/185833?hl=en-GB, because nodemailer needs an access connect to gmail. Next I changed process.env.SMTP_PASSWORD from gmail mail's password to "app's password for your device" - it looks like xxxx-xxxx-xxxx-xxxx code.

    import nodemailer from "nodemailer";
    import dotenv from 'dotenv';
    
    class MailService {
        constructor() {
            dotenv.config();
            this.transporter = nodemailer.createTransport({
                host: process.env.SMTP_HOST,
                port: process.env.SMTP_PORT,
                service: process.env.SMTP_SERVICE,
                secure: true,
                auth: {
                    user: process.env.SMTP_USER,
                    pass: process.env.SMTP_PASSWORD,
                },
            });
        }
    
        async sendActivationMail(to, link) {
            await this.transporter.sendMail({
                from: process.env.SMTP_USER,
                to,
                subject: "Activation account" + process.env.API_URL,
                text: "",
                html: `
                <div>
                    <h1>Activate your account, please</h1>
                    <a href="${link}">${link} </a>
                </div>
                `
            });
        }
    };
    export default new MailService();