Невозможно отправить почту через node-mailer

Итак, я недавно работал над приложением (в java-скрипте), в котором я создавал модуль забытого пароля и сброса пароля.

Я пытался отправить JWT на почту, указанную с помощью службы Mail-trap.

Ниже приведены коды, которые я написал для передачи ...

Забыл пароль

    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('There is no user with the email address', 404));
  }

  // 2) Get Reset Token
  const resetToken = user.createPasswordResetToken();
  await user.save({ validateBeforeSave: false });

  //3 Send Mail to user
  const resetURL = `${req.protocol}://${req.get(
    'host'
  )}/api/v1/users/resetPassword/${resetToken}`;

  const message = `Forgot your password? Submit a PATCH Request to passwordConfirm to : ${resetURL}. \n If you did not send this request please ignore the email`;

  await sendEmail({
    email: user.email,
    subject: 'Your Password Reset Token Valid For 10 Minutes.',
    message
  });

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

Файл email.js

const nodemailer = require('nodemailer');

const sendEmail = async options => {
  // 1) Create 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 Mail Options
  const mailOptions = {
    from: 'Admin <[email protected]>',
    to: options.email,
    subject: options.subject,
    text: options.message
  };

  await transporter.sendMail(mailOptions);
};

module.exports = sendEmail;

У меня нет ошибок кода из кода Visual Studio, я дважды проверял правописание, пока отлаживал код, хотя была одна ошибка, которую я обнаружил при попытке установить nodemailer ...

код ошибки NodeMaile: -

npm я nodemailer

> [email protected] install C:\Users\Kshitij\Desktop\Files\Javascript\Tutorials\BootCamp 2020\complete-node-bootcamp-master\4-natours\starter\node_modules\node-pty
> node scripts/install.js


C:\Users\Kshitij\Desktop\Files\Javascript\Tutorials\BootCamp 2020\complete-node-bootcamp-master\4-natours\starter\node_modules\node-pty>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild )
gyp ERR! find Python
gyp ERR! find Python Python is not set from command line or npm configuration
gyp ERR! find Python Python is not set from environment variable PYTHON
gyp ERR! find Python checking if "python" can be used
gyp ERR! find Python - "python" is not in PATH or produced an error
gyp ERR! find Python checking if "python2" can be used
gyp ERR! find Python - "python2" is not in PATH or produced an error
gyp ERR! find Python checking if "python3" can be used
gyp ERR! find Python - "python3" is not in PATH or produced an error
gyp ERR! find Python checking if the py launcher can be used to find Python 2
gyp ERR! find Python - "py.exe" is not in PATH or produced an error
gyp ERR! find Python checking if Python is C:\Python27\python.exe
gyp ERR! find Python - "C:\Python27\python.exe" could not be run
gyp ERR! find Python checking if Python is C:\Python37\python.exe
gyp ERR! find Python - "C:\Python37\python.exe" could not be run
gyp ERR! find Python
gyp ERR! find Python **********************************************************
gyp ERR! find Python You need to install the latest version of Python.
gyp ERR! find Python Node-gyp should be able to find and use Python. If not,
gyp ERR! find Python you can try one of the following options:
gyp ERR! find Python - Use the switch --python="C:\Path\To\python.exe"
gyp ERR! find Python   (accepted by both node-gyp and npm)
gyp ERR! find Python - Set the environment variable PYTHON
gyp ERR! find Python - Set the npm configuration variable python:
gyp ERR! find Python   npm config set python "C:\Path\To\python.exe"
gyp ERR! find Python For more information consult the documentation at:
gyp ERR! find Python https://github.com/nodejs/node-gyp#installation
gyp ERR! find Python **********************************************************
gyp ERR! find Python
gyp ERR! configure error
gyp ERR! stack Error: Could not find any Python installation to use
gyp ERR! stack     at PythonFinder.fail (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-python.js:307:47)
gyp ERR! stack     at PythonFinder.runChecks (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-python.js:136:21)
gyp ERR! stack     at PythonFinder.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-python.js:225:16)
gyp ERR! stack     at PythonFinder.execFileCallback (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-python.js:271:16)
gyp ERR! stack     at exithandler (child_process.js:310:5)
gyp ERR! stack     at ChildProcess.errorhandler (child_process.js:322:5)
gyp ERR! stack     at ChildProcess.emit (events.js:321:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:273:12)
gyp ERR! stack     at onErrorNT (internal/child_process.js:469:16)
gyp ERR! stack     at processTicksAndRejections (internal/process/task_queues.js:84:21)
gyp ERR! System Windows_NT 10.0.17763
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\Kshitij\Desktop\Files\Javascript\Tutorials\BootCamp 2020\complete-node-bootcamp-master\4-natours\starter\node_modules\node-pty
gyp ERR! node -v v13.6.0
gyp ERR! node-gyp -v v5.0.5
gyp ERR! not ok

> [email protected] postinstall C:\Users\Kshitij\Desktop\Files\Javascript\Tutorials\BootCamp 2020\complete-node-bootcamp-master\4-natours\starter\node_modules\nodemailer
> node -e "try{require('./postinstall')}catch(e){}"

=== Nodemailer 6.4.6 ===

Thank you for using Nodemailer for your email sending needs! While Nodemailer
itself is mostly meant to be a SMTP client there are other related projects in
the Nodemailer project as well.

For example:
> IMAP API (  https://imapapi.com  ) is a server application to easily access
IMAP accounts via REST API
> NodemailerApp (  https://nodemailer.com/app/  ) is a cross platform GUI app to
debug emails

npm WARN [email protected] requires a peer of eslint-plugin-react-hooks@^1.7.0 but none is installed.
You must install peer dependencies yourself.
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\node-pty):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] install: `node scripts/install.js`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1

+ [email protected]
updated 1 package and audited 1285 packages in 11.284s

24 packages are looking for funding
  run `npm fund` for details

found 6 vulnerabilities (5 low, 1 moderate)
  run `npm audit fix` to fix them, or `npm audit` for details

И это последняя ошибка, которую я получаю при отправке API,

    {
        "status": "error",
        "error": {
            "code": "ESOCKET",
            "command": "CONN",
            "statusCode": 500,
            "status": "error"
        },
        "message": "self signed certificate in certificate chain",
        "stack": "Error: self signed certificate in certificate chain\n    at TLSSocket.onConnectSecure (_tls_wrap.js:1474:34)\n    at TLSSocket.emit (events.js:321:20)\n    at TLSSocket._finishInit (_tls_wrap.js:917:8)\n    at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:687:12)"

}

Кто-нибудь, пожалуйста, помогите мне с этим. Это очень важная функция в приложении, из-за которой страдает другой модуль.


person Kshitij Dutt    schedule 26.03.2020    source источник


Ответы (1)


в вашей

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
    }
  });

не могли бы вы добавить

   tls:{
    rejectUnauthorized: false
}

сделать это

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
    },
    tls:{
    rejectUnauthorized: false
    }
  });

это должно решить вашу проблему, так как теперь вы можете самостоятельно пройти аутентификацию

Надеюсь, это устранило вашу проблему. Если у вас по-прежнему возникают проблемы, прочтите это: https://github.com/MarkCavalli/rageserver/issues/51

person Ramsey van der Meer    schedule 27.08.2020