Trialcoder Trialcoder - 3 months ago 41
Node.js Question

Nodemailer not working when sending email in a callback

Following is the code for sending an email via forget password hit, which is not working, however if the same code run via file it is sending an email..let me know what I am doing wrong with the callback usage.

Following is the code, which is working but not sending an email -

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 it is throwing -

{ [Error: connect ECONNREFUSED]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect' }


FYI - I am using
var nodemailer = require("nodemailer");
above the code so that is not the case.

Working code -

Now if I put the same code in a file and run via
node mail.js
command then mail sent successfully.

Let me know what I am doing wrong here if any

Working code (just a duplicate code )

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

Answer

This is not a firewall issue. I am using linemanjs which is hitting the api via proxy and currently proxy is not supported in node mailer.

Nodemailer does not support proxies and currently there is no plan to add any support for these, sorry.

Reference - Nodemailer Issue With Proxy

As a fix I installed nodemailer module on my clientapp(lineman app) and sending data to another app and receive token on the basis of which I am sending email via nodemailer.