NodeJS 无法通过节点邮件程序发送邮件

eufgjt7s  于 2023-03-17  发布在  Node.js
关注(0)|答案(3)|浏览(142)

我最近在开发一个应用程序(用java-script编写),我在其中构建了忘记密码和重置密码模块。
我尝试做的是使用Mail-trap服务向JWT发送指定的邮件。
下面是我写的密码...
忘记密码

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

电子邮件. 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 <e1133140c8-907185@inbox.mailtrap.io>',
    to: options.email,
    subject: options.subject,
    text: options.message
  };

  await transporter.sendMail(mailOptions);
};

module.exports = sendEmail;

我没有来自visual studio代码的代码错误,在调试代码时仔细检查了拼写,尽管在尝试安装nodemailer时发现了一个错误...
错误代码NodeMaile:-
npm i节点邮件程序

> node-pty@0.9.0 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

> nodemailer@6.4.6 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 eslint-config-airbnb@18.0.1 requires a peer of eslint-plugin-react-hooks@^1.7.0 but none is installed.
You must install peer dependencies yourself.
npm WARN nators@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.2 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.1.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: node-pty@0.9.0 (node_modules\node-pty):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: node-pty@0.9.0 install: `node scripts/install.js`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1

+ nodemailer@6.4.6
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)"

}

有人请帮助我这一点。这恰好是一个非常重要的功能,在应用程序,由于另一个模块正在遭受。

u0sqgete

u0sqgete1#

在您的

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

8zzbczxx

8zzbczxx2#

我在mailtrap.io上尝试了这个方法,花了很多时间后,问题是“auth”没有从config.env文件中阅读**“process.env.EMAIL_PASSWORD”**。

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

所以我不得不像这样在auth中手动写入它,并将端口更改为578

const transporter = nodemailer.createTransport({
    host: process.env.EMAIL_HOST,
    port: process.env.EMAIL_PORT,
    auth: {
        user: process.env.EMAIL_USERNAME,
        pass: "8d984726187121"
    }
});
0vvn1miw

0vvn1miw3#

我也收到了同样的错误

Error: connect ETIMEDOUT 3.209.246.195:587
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16)
{  
errno: -4039,  
code: 'ESOCKET',  
syscall: 'connect',  
address: '3.209.246.195',  
port: 587,
command: 'CONN'
}

我试着调试了一个小时。然后我换了我的互联网,它修复了这个问题。互联网速度慢是我的问题。但错误是一样的。超时。

相关问题