Unable to send mail through node mailer. Error: connect ECONNREFUSED at port 25"

Unable to send mail through node mailer. Error: connect ECONNREFUSED at port 25"

每次我提出忘记密码请求时,它都会给我这个错误,并且邮件永远不会发送到 Mailtrap。

Nodemailer 设置 这是我所做的基本节点邮件程序设置。

端口=25

const nodemailer = require('nodemailer');

const sendEmail = async (options) => {
  // 1) Create a Transporter
  const transporter = nodemailer.createTransport({
    host: process.env.EMAIL_HOST,
    port: process.env.EMAIL_PORT,
    auth: {
      user: process.env.EMAIL_USERNAME,
      pass: process.env.EMAIL_PASSWORD,
    },
  });

  // 2) Define the email Options
  const mailOptions = {
    from: 'Sachin Yadav <sachin.yadav@gmail.com',
    to: options.email,
    subject: options.subject,
    text: options.text,
  };

  // 3) Send the email
  await transporter.sendMail(mailOptions);
};

忘记密码功能

catchAsync 只是一个包装函数,它的创建只是为了单独捕获异步错误。它 returns 异步函数传入它并使用 req、res 和 next 参数调用它。

exports.forgotPassword = catchAsync(async (req, res, next) => {
  // 1) Get user based on posted email
  const user = await User.findOne({ email: req.body.email });

  if (!user)
    return next(
      new AppError('No user with that email. Please try again!', 404)
    );

  // 2) Generate Random
  const resetToken = user.createPasswordResetToken();
  await user.save({ validateBeforeSave: false });

  // 3) Send back the token on email
  const resetURL = `${req.protocol}://${req.get('host')}/api/v1/users/resetPassword/${resetToken})}`;

  const message = `Forgot your password? Submit a PATCH request with your new password and passwordConfirm to : ${resetURL}`;

  // Send Email
  try {
    await sendEmail({
      email: user.email,
      subject: 'Password reset link (Valid for 10mins)',
      message,
    });

    res.status(200).json({
      status: 'success',
      message: 'Token send',
    });

    // Err
  } catch (err) {
    // Set back the token and expire time
    user.createPasswordResetToken = undefined;
    user.passwordResetExpires = undefined;
    await user.save({ validateBeforeSave: false });

    return next(
      new AppError(`There was an error sending the email ${err.message}`, 500)
    );
  }
});

我刚刚将端口从 25 更改为 2525,出于某种原因,它起作用了。如果有人知道为什么会这样,请告诉我。

一个原因可能是其他应用程序正在使用您系统中的端口“25”。如果您使用的是 Windows PC,您可以使用以下命令检查正在使用的端口(您需要以管理员身份打开 cmd):

netstat -aon