在expressjs中使用Nodemailer出错?

时间:2017-03-08 14:29:36

标签: node.js mongodb email express nodemailer

我使用Nodemailer设置忘记密码功能。出于某种原因,我的代码被挂起在smtpTrans.sendMail部分。我是否正确设置了Nodemailer?

更新:请查看下面的完整代码,包括async.waterfall代码

app.post('/forgot', function(req, res, next) {
  async.waterfall([
    function(done) {
      crypto.randomBytes(20, function(err, buf) {
        var token = buf.toString('hex');
        done(err, token);
      });
    },
    function(token, done) {
      User.findOne({ email: req.body.email }, function(err, user) {
        if (!user) {
          console.log('error', 'No account with that email address exists.');
          return res.redirect('/forgot');
        }
console.log('step 1')
        user.resetPasswordToken = token;
        user.resetPasswordExpires = Date.now() + 3600000; // 1 hour

        user.save(function(err) {
          done(err, token, user);
        });
      });
    },
    function(token, user, done) {
        console.log('step 2')
      var smtpTrans = nodemailer.createTransport({
         service: 'Hotmail', 
        auth: {
          user: 'myemailinfo@email.com',
          pass: '**********'
        }
      });
      var mailOptions = {

        to: user.email,
        from: 'myemailinfo@email.com',
        subject: 'Node.js Password Reset',
        text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
          'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
          'http://' + req.headers.host + '/reset/' + token + '\n\n' +
          'If you did not request this, please ignore this email and your password will remain unchanged.\n'

      };
      console.log('step 3')
   smtpTrans.sendMail(mailOptions, function(err) {
       console.log(err)
        req.flash('info', 'An e-mail has been sent to ' + user.email + ' with further instructions.');
        done(err, 'done');
      });
    }
  ], function(err) {
    if (err) return next(err);
    console.log(err)
    res.redirect('/forgot');
  });
});

app.get('/forgot', function(req, res) {
  res.render('forgot', {
    user: req.user
  });
});

1 个答案:

答案 0 :(得分:1)

节点制作者documentation表示提供给callback的{​​{1}}获取第二个参数sendMail。所以你可能会尝试这样的事情:

info

如果调用了回调,则可以使用SMTP邮件程序中的某些响应来填充smtpTrans.sendMail(mailOptions, function(err, info) { if (err) { console.log(err) } if (info) { console.log(info.response) } req.flash('info', 'An e-mail has been sent to ' + user.email + ' with further instructions.'); done(err, 'done'); }); ,以便为您提供无法按预期工作的指示。

如果从不调用回调,则可能是服务没有响应,并且调用没有超时。您还可以在SMTP options

中提供自定义超时值

最后一点:Hotmail通过SMTP每日限制为100条消息,因此您应该考虑使用其他提供商。