简体   繁体   English

无法通过 node-mailer 发送邮件

[英]Unable to Send Mail through node-mailer

So I was recently working on an app(in java-script) where I was building the forgot-password and reset-password Module.所以我最近正在开发一个应用程序(在 java-script 中),我正在构建忘记密码和重置密码模块。

What I was trying to do was to send an JWT the mail specified using the Mail-trap service.我试图做的是向 JWT 发送使用 Mail-trap 服务指定的邮件。

Down below are the codes where that I have written to pass...下面是我写的要通过的代码...

Forgot Password忘记密码

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

The email.js file 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;

I have no code errors from the visual studio code, have double checked spellings while I was debugging the code, though there was one error that I found while trying to install nodemailer...我没有来自 Visual Studio 代码的代码错误,在调试代码时仔细检查了拼写,尽管我在尝试安装 nodemailer 时发现了一个错误...

error code NodeMaile: -错误代码 NodeMaile: -

npm i nodemailer npm i nodemailer

> 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

And this is the final error i get when send the API,这是我发送 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)"

}

Someone please help me with this.有人请帮我解决这个问题。 This happens to be an very important functionality in the app due to which another module is suffering.这恰好是应用程序中非常重要的功能,因为另一个模块正在遭受痛苦。

in your在你的

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

could you add你能补充一下吗

   tls:{
    rejectUnauthorized: false
}

to make it使它

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

this should fix your problem as you can now self authenticate yourself这应该可以解决您的问题,因为您现在可以自我验证自己

Hopefully, this fixed your problem.希望这解决了您的问题。 If you are still having problems give this a read: https://github.com/MarkCavalli/rageserver/issues/51如果您仍然遇到问题,请阅读: https : //github.com/MarkCavalli/rageserver/issues/51

I was trying this with mailtrap.io and after spending much time the problem was that the "auth" was not reading the "process.env.EMAIL_PASSWORD" from the config.env file.我正在用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"
    }
});

So I had to write it manually in the auth like this and also changed port to 578所以我不得不像这样在身份验证中手动编写它,并将端口更改为 578

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM