"Client network socket disconnected before secure TLS connection was established" error in nodemailer - express

I want to setup contact form, that's why I am using node mailer and postman for testing purpose but, i am receiving this error
Client network socket disconnected before secure TLS connection was established
Here is my code:
const transporter = nodemailer.createTransport({
host: 'smtp.itcarver.com',
port: 587,
secure: false,
auth: { user: 'support#itcarver.com', pass: 'xyz' },
tls: { rejectUnauthorized: false }
});
const mailOptions = {
from: 'support#itcarver.com',
to: "xyz",
subject: "subject",
text: "test",
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error)
res.send("error");
} else {
res.send('Email sent: ');
}
});
And here is the error:
Error: Client network socket disconnected before secure TLS connection was established
at connResetException (internal/errors.js:604:14)
at TLSSocket.onConnectEnd (_tls_wrap.js:1513:19)
at Object.onceWrapper (events.js:417:28)
at TLSSocket.emit (events.js:323:22)
at endReadableNT (_stream_readable.js:1204:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'ESOCKET',
path: undefined,
host: 'smtp.itcarver.com',
port: undefined,
localAddress: undefined,
command: 'CONN'
}

You may need to set tls maxVersion to some other than default (which is TLSv1.3). It was necessary in my case.
tls: { maxVersion: 'TLSv1.2' }

Related

Error: self-signed certificate When connecting to google FCM with XMPP protocol

I am trying to connect to google Firebase Messaging with xmpp protocol with Node Js with node-xmpp-client
But I am getting an TLS error
Below is the code:
const XMPP = require("node-xmpp-client");
config = {
id: "push-notify-xmpp",
key: "________KEY______",
port: "5236",
host: "fcm-xmpp.googleapis.com",
};
client = new XMPP.Client({
jid: `${config.id}#fcm-xmpp.googleapis.com`,
password: config.key,
port: config.port,
host: config.host,
legacySSL: true,
preferredSaslMechanism: "PLAIN",
});
client.connection.socket.on("error", function (error) {
console.log("socket error");
console.error(error);
process.exit(1);
});
client.on("online", function (data) {
console.log(
"Connected as " +
data.jid.local +
"#" +
data.jid.domain +
"/" +
data.jid.resource
);
});
client.on("error", function (err) {
console.log("server error");
console.error(err);
process.exit(1);
});
Error:
server error
Error: self-signed certificate
at TLSSocket.onConnectSecure (node:_tls_wrap:1538:34)
at TLSSocket.emit (node:events:513:28)
at TLSSocket._finishInit (node:_tls_wrap:952:8)
at ssl.onhandshakedone (node:_tls_wrap:733:12) {
code: 'DEPTH_ZERO_SELF_SIGNED_CERT'
}
Also tried the command :
NODE_TLS_REJECT_UNAUTHORIZED='0' node appServer.js
But above get an different error Unauthorised
Can Anyone have any Idea ow to deal with FCM server with XMPP

Express-session uses Redis. When Redis stops, the request is blocked

In NestJS, I use Express-Session and use Redis as Store.
The Redis address is a load balancing address. When I offline the Redis server, I sent a new request and found that I had been loading until timeout. I want to return the response after the redis error is detected.
const RedisStore = connectRedis(session);
const redisClient = new Redis('redis://****:6379');
redisClient.on('error', (err) => {
console.error(err);
});
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(
session({
store: new RedisStore({ client: redisClient }),
secret: 'asdasdasd',
resave: false,
saveUninitialized: false,
cookie: { httpOnly: true, maxAge: 1000 * 60 * 10 },
}),
);
redis error
Error: connect ETIMEDOUT
at Socket.<anonymous> (/Users/code/nestjs-session/node_modules/ioredis/built/Redis.js:168:41)
at Object.onceWrapper (events.js:312:28)
at Socket.emit (events.js:223:5)
at Socket._onTimeout (net.js:474:8)
at listOnTimeout (internal/timers.js:531:17)
at processTimers (internal/timers.js:475:7) {
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect'
}
try with redis legacy mode
const redis = createClient({ socket: { host: "localhost", port: 6379 }, legacyMode: true });

Undefined return when send email using nodemailer package

I am trying to send email with javascript nodemailer package but returning undefined.
Checked following options:
Less app secured is ON
No 2 Factor enabled
enabled https://accounts.google.com/DisplayUnlockCaptcha
Let me know what is missing ?
I have followed all possible noted on this website but could not help me.
Code
async sendEmailWithAttachments(
fromemailid,
toemailid,
fileName,
attachmentsPath
) {
let transporter = nodemailer1.createTransport({
// service: "gmail",
host: "smtp.gmail.com",
port: 587,
secure: false,
debug: true,
auth: {
user: "XXX#gmail.com",
pass: "XXXX",
},
tls: {
rejectUnauthorized: false,
},
logger: true,
});
let mailOptions = {
from: "XXX#gmail.com",
to: "XXX#gmail.com",
subject: "Hello ✔", // Subject line
text: "Hello world?", // plain text body
// attachments: [
// {
// // utf-8 string as an attachment
// filename: fileName,
// path: attachmentsPath,
// },
// ],
};
// send mail with defined transport object
let info = transporter.sendMail(mailOptions, (error, success) => {
if (error) {
console.log(error);
}
});
console.log("================= Mail sent ===============", info);
}
Here info object shows undefinded
Here Console log:
[0-0] [2022-05-31 05:52:03] DEBUG Sending mail using SMTP/6.7.5[client:6.7.5]
[0-0] ================= Mail sent =============== **undefined**
[0-0] 2022-05-31T05:52:03.787Z DEBUG #wdio/utils:shim: Finished to run "afterTest" hook in 0ms
[0-0] 2022-05-31T05:52:03.796Z INFO webdriver: COMMAND deleteSession()
[0-0] 2022-05-31T05:52:03.796Z INFO webdriver: [DELETE] http://localhost:9515/session/cfa202e5063720bed6ff7fa47b29f96d
[0-0] [2022-05-31 05:52:03] DEBUG [5nz3hZn0uA] Resolved smtp.gmail.com as XX.XXX.XXX.XXX [cache miss]
[0-0] [2022-05-31 05:52:03] INFO [5nz3hZn0uA] Connection established to XX.XXX.XXX.XXX:587```

Problem with setting up oauth2 with nodemailer

I am building mail form with react, express and nodemailer and i have a problem.
How to set up oauth2? I have some
Error: invalid_grant
This is my code:
async function main2() {
const output = `Some output text...`;
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: 'mail.google.com',
port: 465,
secure: true, // true for 465, false for other ports
auth: {
type: 'OAuth2',
clientId: 'clientID here',
clientSecret: 'clientSecret here',
refreshToken: 'refreshToken here',
accessToken: 'accessToken here',
expires: number
},
tls: {
rejectUnauthorized: false
}
});
// send mail with defined transport object
let info = await transporter.sendMail({
to: {
name: 'Me',
address: `${req.body.email}`
},
auth: {
user: 'mymail#gmail.com',
},
subject: 'Hello',
html: output // html body
});
console.log('Message sent: %s', info.messageId);
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321#example.com>
// Message sent to:...
console.log(`Message sent to: ${req.body.email}`)
// Preview only available when sending through an Ethereal account
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}
main2().catch(console.error);
})
I am getting this error and i dont know what am I missing.
Im new in nodemailer and express and any help would be appreciated.
{ Error: invalid_grant
at postRequest (path/node_modules/nodemailer/lib/xoauth2/index.js:259:33)
at PassThrough.req.once (path/node_modules/nodemailer/lib/xoauth2/index.js:328:20)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:111:20)
at PassThrough.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9) code: 'EAUTH', command: 'AUTH XOAUTH2' }

Send email using Nodemailer with GoDaddy hosted email

I am trying to send an email using nodemailer and a custom email address configured through GoDaddy. Here is a screen shot of the "custom configurations" page in c-panel:
and my code:
const nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'Godaddy',
secureConnection: false,
auth: {
user: 'info#mywebsite.com',
pass: 'mypassword'
}
});
var mailOptions = {
from: 'info#mywebsite.com',
to: 'otheremail#gmail.com',
subject: 'Sending Email using Node.js',
text: 'That was easy!',
html: '<h1>Welcome</h1><p>That was easy!</p>'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
and my error log:
{ Error: connect EHOSTUNREACH 173.201.192.101:25
at Object.exports._errnoException (util.js:1012:11)
at exports._exceptionWithHostPort (util.js:1035:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1080:14)
code: 'ECONNECTION',
errno: 'EHOSTUNREACH',
syscall: 'connect',
address: '173.201.192.101',
port: 25,
command: 'CONN' }
I've tried changing the port number, making it secure vs non-ssl, using my website address as the host, and pretty much everything else I can think of. I have successfully sent an email from the godaddy email using one of the webmail clients. Has anyone else ever encountered this or have recommendations on things to try?
I am trying to send emails using nodemailer from Google Cloud Function using GoDaddy SMTP settings. I do not have Office365 enabled on my GoDaddy hosting. None of the above options worked for me today (12 November 2019). TLS need to be enabled.
I had to use the following configuration:
const mailTransport = nodemailer.createTransport({
host: "smtpout.secureserver.net",
secure: true,
secureConnection: false, // TLS requires secureConnection to be false
tls: {
ciphers:'SSLv3'
},
requireTLS:true,
port: 465,
debug: true,
auth: {
user: "put your godaddy hosted email here",
pass: "put your email password here"
}
});
Then, I could send a test email as follows:
const mailOptions = {
from: `put your godaddy hosted email here`,
to: `bharat.biswal#gmail.com`,
subject: `This is a Test Subject`,
text: `Hi Bharat
Happy Halloween!
If you need any help, please contact us.
Thank You. And Welcome!
Support Team
`,
};
mailTransport.sendMail(mailOptions).then(() => {
console.log('Email sent successfully');
}).catch((err) => {
console.log('Failed to send email');
console.error(err);
});
you should make some changes in your transporter:
var smtpTrans = nodeMailer.createTransport({
service: 'Godaddy',
host: "smtpout.secureserver.net",
secureConnection: true,
port: 465,
auth: {
user: "username",
pass: "password"
}
});
I realize this is an old post, but just wanted to add to this since the GoDaddy SMTP server has changed, just in case someone else comes across this and has the same problem I had. The answer by #tirmey did not work for me, but this did.
let nodemailer = require('nodemailer');
let mailerConfig = {
host: "smtp.office365.com",
secureConnection: true,
port: 587,
auth: {
user: "username#email.com",
pass: "password"
}
};
let transporter = nodemailer.createTransport(mailerConfig);
let mailOptions = {
from: mailerConfig.auth.user,
to: 'SomePerson#email.com',
subject: 'Some Subject',
html: `<body>` +
`<p>Hey Dude</p>` +
`</body>`
};
transporter.sendMail(mailOptions, function (error) {
if (error) {
console.log('error:', error);
} else {
console.log('good');
}
});
Solutions proposed above seem no longer valid, none of them worked for me. Following solution works for me:
const nodemailer = require('nodemailer');
const os = require('os');
let mailerConfig = {
host: os.hostname(),
port: 25,
};
let transporter = nodemailer.createTransport(mailerConfig);
transporter.sendMail({
from: '<from>',
to: '<to>',
subject: '<subject>',
text: '<text>'
}, (err, info) => {
console.log(info);
console.log(err);
});
I could solve the problem by using this code and some points that I brought them after codes:
const smtpTransport = nodemailer.createTransport({
host: "smtp.office365.com",
secure: false,
port: 587,
auth : {
user : 'info#my-domain.com',
pass : 'Password'
}
});
const mailOptions = {
to: 'target-mail#',
subject: 'Test 01',
html: 'Body',
from : 'info#resoluship.com'
};
await smtpTransport.sendMail(mailOptions);
Don't forget to use 'from' attribute in mailOptions
Don't use ',' in your 'from' attribute
For me, the solution for production shared hosting server was completely different than for testing.
It seems no authentication or credentials are required for it to work.
I created this code from this document describing how to use an SMTP relay server. You can use this with nodemailer. GoDaddy support told me I couldn't but I don't think they know about third party tools.
https://au.godaddy.com/help/send-form-mail-using-an-smtp-relay-server-953
async function main() {
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: 'localhost', //use localhost for linux cPanel hosting
port: 25,
secure: false,
// no need for authentication
tls: {
rejectUnauthorized: false
}
});
// send mail with defined transport object
let info = await transporter.sendMail({
to: "you#youremail.com", // list of receivers
subject: `New Message from ${name}`, // Subject line
text: `yourtext`, // plain text body
html: `your text in html`, // html body
headers: {
priority: 'high'
},
from: "you#youremail.com" // sender address
});
// send success page if successful
if (res.statusCode === 200) {
res.sendFile(path.join(__dirname, 'views/success.ejs'))
}
console.log("Message sent: %s", info.messageId, res.statusCode);
}
main().catch(console.error);
The most common problem with this error is the antivirus. So disable it for 10 minutes if you are testing it locally.