以下是通过忘记密码命中发送电子邮件的代码,它不起作用,但是如果通过文件运行相同的代码,它正在发送电子邮件..让我知道我在使用回调时做错了什么。
以下是代码,它正在工作但不发送电子邮件 -
app.post('/forget', function(req, res){
var userEmail = req.body.email;
User.findOne({email: userEmail}, function(err, user){
if (err) {
res.send({"message": "Wrong!", "err": err, "status_code": "500"});
}
else{
var password = "12345";
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "XXXXX@gmail.com",
pass: "YYYYY"
}
});
var mailOptions = {
from: "Team | <XXXXX@gmail.com>",
to: user.email,
subject: "Password Change",
text: "Hello world",
html: "Your password changed successfully."+ "Your new password is "+ "<style='color: red;'>"+ password +"</style>" // html body
};
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
}else{
console.log("Message sent: " + response.message);
}
});
user.password = password;
user.save(function(err){
if (err) return handleError(err);
else return res.send({"message": "success", "data": user, "status_code": "200"});
});
}
});
});
它抛出的错误 -
{ [Error: connect ECONNREFUSED]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect' }
仅供参考 - 我var nodemailer = require("nodemailer");
在代码上方使用,所以情况并非如此。
工作代码 -
现在,如果我将相同的代码放在一个文件中并通过node mail.js
命令运行,那么邮件发送成功。
如果有的话,让我知道我在这里做错了什么
工作代码(只是重复代码)
var password = "12345";
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "XXXXX@gmail.com",
pass: "YYYYY"
}
});
var mailOptions = {
from: "Team | <XXXXX@gmail.com>",
to: user.email,
subject: "Password Change",
text: "Hello world",
html: "Your password changed successfully."+ "Your new password is "+ "<style='color: red;'>"+ password +"</style>" // html body
};
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
}else{
console.log("Message sent: " + response.message);
}
});