Search code examples
javascriptnode.jssmtpnodemailer

SMTP NodeMailer sends emails in localhost but not on production server


I'm trying to send user verification emails after sign ups.

The app is built using Node.JS and JavaScript, and I'm using SMTP and Nodemailer NPM Module to send the emails.

The code below works fine and sends email correctly when testing locally in 'localhost' on my PC, but won't work when uploaded on the production server.

I've contacted my web host and they say the configurations are set correctly.

The code gives the error:


{ Error: connect ECONNREFUSED 198.xx.xxx.xxx
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1107:14)
  errno: 'ECONNREFUSED',
  code: 'ESOCKET',
  syscall: 'connect',
  address: '198.xx.xxx.xxx',
  port: 465,
  command: 'CONN' }

And again the code sends emails fine when running locally on my PC.

Could you please help me identify the issue with this code?

Thanks in advance!


const sendMsg = async (receiver, title, msg) => {

    // Define configurations for the SMTP Server.
    var smtpTransport = nodemailer.createTransport({
       host: "mail.privateemail.com",
       secure: true,
       port: 465, 
       auth: {
            user: "myxxxxx@company.com",
            pass: "mypassword"
        }
    });

    // Define message parameters
    var mailOptions={
        from: "My Company <myxxxxx@company.com>",
        to : receiver,
        subject : title,
        text : "",
        html : msg 
    }

    // Send email to client
    var mailSent = await smtpTransport.sendMail(mailOptions)
    .then((response) => {return true;})
    .catch(err => { console.log(err); return false;});

    return mailSent
};


Solution

  • The above code works fine.

    I had to contact my webhost to ask them to open port 465.

    I didn't know the code will work fine during localhost testing, even if port 465 is closed on the production server.

    That said, my webhost opened port 465 on the server and the code now sends emails fine even on the production server.