I am trying to send email from NodeJS using out office MS Exchange Mail server. with below code. And get error
Our Admin said no certificates are needed.
Error:-
$ node test2.js
Error : { Error: unable to verify the first certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1048:34)
at TLSSocket.emit (events.js:182:13)
at TLSSocket._finishInit (_tls_wrap.js:628:8) code: 'ESOCKET', command: 'CONN' }
NodeJS Code:-
"use strict";
const nodemailer = require("nodemailer");
async function main() {
try {
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: 'host',
port: 25,
secure : false, // true for 465, false for other ports
auth: {
user: 'user',
pass: 'password'
}
});
// setup email data
let mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Hey you, awesome!',
html: '<b>This is bold text</b>',
text: 'This is text version!'
};
// send mail with defined transport object
let info = await transporter.sendMail(mailOptions)
console.log("Message sent: %s", JSON.stringify(info));
} catch (error) {
console.log('Error : ', error);
}
}
main(); // For testing
The “error:num=21:unable to verify the first certificate” means that chain of trust is broken right from the start. Typically it might happen if the certificate doesn't include intermediate certificates, or if it has the wrong intermediate certificate.
tls – defines additional node. js TLSSocket options to be passed to the socket constructor, eg. {rejectUnauthorized: true}. tls.servername - is optional hostname for TLS validation if host was set to an IP address.
In the localhost its not working because a secure and safetly connection is required for sending an email but using gmail[smtp(simple mail transfer protocol)] we can achieve it functionality. Don't forget to first do the setting - Allow less secure apps to access account. its given permission for access gmail account.
Available from Nodemailer v5.1.0. Nodemailer SMTP client can be extended to use custom authentication mechanisms that Nodemailer does not support by default. To use one you should define a custom authentication handler with customAuth in the transporter options. Multiple handlers can be defined.
The below code change fixed the issue. Added this to the createTransport()
tls: {rejectUnauthorized: false}
Code:-
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: 'host',
port: 25,
secure : false, // true for 465, false for other ports
auth: {
user: 'user',
pass: 'password'
},
tls: {
// do not fail on invalid certs
rejectUnauthorized: false
},
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With