'Error: connect ECONNREFUSED 127.0.0.1:587 – nodemailer & gmail

Dear stack overflow community,

I am dealing with a project and I tried many things, but I can't handle it.

I created a website with NextJS. This Website has a contact form. To send the data from the contact form to the addressee, there is an API which takes the request and with nodemailer I am trying to create a transporter to send the email with Gmail.

const nodemailer = require("nodemailer");
const { google } = require("googleapis");

export default async function (req, res) {
  const body = JSON.parse(req.body);

  const CLIENT_EMAIL = process.env.CLIENT_EMAIL;
  const CLIENT_ID = process.env.CLIENT_ID;
  const CLIENT_SECRET = process.env.CLIENT_SECRET;
  const REDIRECT_URI = process.env.REDIRECT_URI;
  const REFRESH_TOKEN = process.env.REFRESH_TOKEN;

  const OAuth2Client = new google.auth.OAuth2(
    CLIENT_ID,
    CLIENT_SECRET,
    REDIRECT_URI
  );

  OAuth2Client.setCredentials({ refresh_token: REFRESH_TOKEN });

  try {
    // Generate the accessToken on the fly
    const accessToken = await OAuth2Client.getAccessToken();

    // Account authentication config
    const authConfig = {
      type: "OAuth2",
      user: CLIENT_EMAIL,
      clientId: CLIENT_ID,
      clientSecret: CLIENT_SECRET,
      refreshToken: REFRESH_TOKEN,
      accessToken: accessToken,
    };

    // Create the email envelope (transport)
    const transport = nodemailer.createTransport(authConfig);

    // Create the email options and body
    // ('email': user's email and 'name': is the e-book the user wants to receive)
    const mailOptions = {
      from: `${CLIENT_EMAIL}`,
      to: body.email,
      subject: `${body.name} – ${body.reason}`,
      text: `${body.message}`,
    };

    const result = await transport.sendMail(mailOptions);
    return result;
  } catch (error) {
    console.log(error);
  }

  res.status(200).json({
    message: "Email has been sent",
  });
}

The problem is, when the User sends the email, I get the following error message:

Error: connect ECONNREFUSED 127.0.0.1:587
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1161:16) {
  errno: -61,
  code: 'ESOCKET',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 587,
  command: 'CONN'
}

I tried a couple of things now, but I really do not make any progress at this point. I would be super happy if somebody could help me.

Thanks a lot in advance.



Solution 1:[1]

Just make http://localhost:8000 to http://127.0.0.1:8000. It works. Windows are not configured to figure this out. An IP address should be in the conventions of numbers.

http://127.0.0.1:8000

The above address is the default one for any computer

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bitfinicon