Search code examples
javascriptjsonnode.jsresponsenodemailer

NodeJS - Nodemailer not able to response.json when message sent


I am trying to achieve a working contact form using nodemailer in NodeJS. The whole setup was actually working. It is just that I am not able to send back the response to the client side. What am I missing here?

Below is my code:

JS

app.post('/contact', function(request,response){
    var mailOptions = {
        from: request.body.email, 
        to: user,
        subject: request.body.names, 
        generateTextFromHTML: true,
        html: request.body.message 
    }
    smtpTransport.sendMail(mailOptions, function(error, response){
        if(error){
            console.log(error);
        }else{
            console.log("Message sent: " + response.message);
            response.json(response.message);
        }
        smtpTransport.close();
    });
});

Error:

TypeError: undefined is not a function at MailerComposer.returnCallback,

pointing at the line code response.json(response.message);

Message Sent result : 250 2.0.0 OK 1438964613 e4sm153473pdd.45 - gsmtp


Solution

  • Found an answer to my question. From my code, the variable response was being called in a wrong order. By changing the variable inside the smtpTransport function solves it.

    Answer:

    smtpTransport.sendMail(mailOptions, function(error, res){
        if(error){
            console.log(error);
        }else{
            console.log("Message sent: " + res.message);
            response.json(res.message);
        }
        smtpTransport.close();
    });