sending email failed from NodeJS - node.js

I am trying to send mail from my NodeJS backend application, but am getting some error :-
Error: self signed certificate in certificate chain
at TLSSocket.onConnectSecure (_tls_wrap.js:1497:34)
at TLSSocket.emit (events.js:315:20)
at TLSSocket._finishInit (_tls_wrap.js:932:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:706:12) {
code: 'ESOCKET',
command: 'CONN'
How can I fix this? The same function is working in some other machines (in local) I think am missing something to configure or install..!
sendMail() {
try {
let info = await this.transporter.sendMail({
from: 'sender#address.com',
to: user.email,
subject: "Subject",
html: `<p>mail content</p>`,
attachments: [{
filename: 'logo.png',
path: join(__dirname, '..images/logo.png'),
}]
});
} catch (error) {
return console.error(error);
}
}

Related

Nodejs - ERR_TLS_CERT_ALTNAME_INVALID

I have called this function below:
export async function getStaticProps() {
const res = await fetch("https://links.papareact.com/pyp");
const exploreData = await res.json();
return {
props: {
exploreData,
},
};
}
And it is showing the error below. How do I solve this issue?
Server Error
FetchError: request to https://jsonkeeper.com/b/4G1G failed, reason: Hostname/IP does not match certificate's altnames: Host: jsonkeeper.com. is not in the cert's altnames: DNS:www.jsonkeeper.com
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
ClientRequest.
file:///P:/Work/Web%20Development/airbnb-clone/node_modules/next/dist/compiled/node-fetch/index.js (1:65756)
ClientRequest.emit
node:events (527:28)
TLSSocket.socketErrorListener
node:_http_client (454:9)
TLSSocket.emit
node:events (527:28)
emitErrorNT
node:internal/streams/destroy (157:8)
emitErrorCloseNT
node:internal/streams/destroy (122:3)
processTicksAndRejections
node:internal/process/task_queues (83:21)your text
I was trying to call an api but its showing
type: 'system',
errno: 'ERR_TLS_CERT_ALTNAME_INVALID',
code: 'ERR_TLS_CERT_ALTNAME_INVALID',
I have installed mkcert but the problem was not solved.
You just need to add www to the jsonkeeper link
export async function getStaticProps() {
const res = await fetch('https://www.jsonkeeper.com/b/4G1G');
const exploreData = await res.json();
return {
props: {
exploreData,
},
};
}

sp-request : trying get file details from sharepoint returns ECONNREFUSED

I have the following code that successfully uploads test.sspkg to my sharepoint app catalog. Now I'm trying to use sp-request to prove that it's actually there.
But I'm getting an ECONNREFUSED error.
Error message
This shows the error:
[14:24:15] INFO: Checking if file (test.sppkg) is checked out
[14:24:15] INFO: File checkout type: 0
[14:24:17] Published file 1482ms
[14:24:17] And we're done...
trying to retrieve: https://mytenant.sharepoint.com/sites/JJTest/_api/web/GetFileByServerRelativeUrl(#FileUrl)/$value?#FileUrl='%2Fsites%2FJJTest%2FAppCatalog%2Ftest.sppkg'
errored out
{ GotError: connect ECONNREFUSED 127.0.0.1:443
at onError (/src/myplugins/node_modules/got/dist/source/request-as-event-emitter.js:140:29)
at ClientRequest.request.on.error (/src/myplugins/node_modules/got/dist/source/request-as-event-emitter.js:157:17)
at ClientRequest.emit (events.js:203:15)
at ClientRequest.EventEmitter.emit (domain.js:448:20)
at ClientRequest.origin.emit.args (/src/myplugins/node_modules/#szmarczak/http-timer/dist/source/index.js:43:20)
at TLSSocket.socketErrorListener (_http_client.js:401:9)
at TLSSocket.emit (events.js:198:13)
at TLSSocket.EventEmitter.emit (domain.js:448:20)
at emitErrorNT (internal/streams/destroy.js:91:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1107:14) name: 'RequestError', code: 'ECONNREFUSED' }
Package
This is the node package I'm using to call the SP API:
"dependencies": {
"sp-request": "^3.0.0"
}
Code:
const sprequest = require('sp-request');
await new Promise((resolve, reject) => {
gulp
.src(folderLocation)
.pipe(
spsync({
username: uname,
password: pwd,
site: siteCatalogUrl + "/",
libraryPath: catalogName,
publish: true,
verbose: true
}))
.on("finish", () => {
var spr = sprequest.create({ username: uname, password: pwd });
//https://mytenant.sharepoint.com/sites/JJTest/_api/web/getFileByServerRelativeUrl('/sites/JJTest/AppCatalog/test.sppkg')
var filepath = `${siteCatalogUrl}/_api/web/GetFileByServerRelativeUrl(#FileUrl)/$value?#FileUrl='${encodeURIComponent("/sites/JJTest/AppCatalog/test.sppkg")}'`;
console.log('trying to retrieve: ' + filepath);
var retrieveFileUrl = filepath;
spr.get(filepath, {
encoding:null
})
.then(data => {
expect(fileContent.equals(data.body)).is.true;
resolve();
})
.catch(data => {
console.log('errored out')
console.log(data)
reject();
});
resolve();
});
});
What I've tried:
I have tried just copying parts of the output from my console directly into the browser. Specifically, this is the output i get from my debug print statement:
trying to retrieve: https://mytenant.sharepoint.com/sites/JJTest/_api/web/GetFileByServerRelativeUrl/(#FileUrl)/$value?#FileUrl='%2Fsites%2FJJTest%2FAppCatalog%2Ftest.sppkg'
errored out
Pasting this:
https://mytenant.sharepoint.com/sites/JJTest/_api/web/GetFileByServerRelativeUrl('/sites/JJTest/AppCatalog/test.sppkg')
into a browser as the URL works. It returns the details of the file to me.
Can you tell me where I've gone wrong? maybe the syntax of substituting the #FileUrl?
I am using gulp version 3.9.1. And I just did a install latest of chai and sp-request.
But tried changing the specific versions to:
"sp-request": "^2.1.3"
"gulp": "^3.9.1",
"gulp-spsync-creds": "2.3.8",
"chai": "3.5.0"
And now, it's happy! it worked!

I am trying to setup a Node.js FTP Server that can pull data from another FTP server

Rule:
Node.js Server will pull data from another FTP server retrieving a .csv file.
I keep getting this error:
Error: unable to verify the first certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1497:34)
at TLSSocket.emit (events.js:315:20)
at TLSSocket._finishInit (_tls_wrap.js:932:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:706:12) {
code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'
The code is as follows:
const ftp = require("basic-ftp");
(async function () {
const client = new ftp.Client();
client.ftp.verbose = true;
try {
await client.access({
host: "host",
user: "user",
password: "pass",
secure: true,
strictSSL: false,
});
console.log(await client.list());
await client.uploadFrom("VEHICLES.csv");
await client.downloadTo("VEHICLES.csv");
} catch (err) {
console.log(err);
}
client.close();
})();
A beer to whoever can help me out..
UPDATE
add in .access options:
secureOptions: {
rejectUnauthorized: false
}

Nodemail x Node.js: Failed auth although tested with success

I am having a problem with a nodemailer Firebase Function supposed to send emails through an SMTP transporter.
It is strange because I am testing my connection with success using:
// check server readiness
const serverReady = await new Promise<boolean>(resolve => {
transporter.verify( (err: any, succ: any) => {
if (err) {
console.log(err);
resolve(false);
} else {
console.log('Server is ready to take our messages');
resolve(true);
}
});
})
Which prints Server is ready to take our messages.
Then after setting up my envelope andsending it with th .sendMail method I get this error:
Unhandled error { Error: Mail command failed: 530 5.5.1 Authentication Required.
at SMTPConnection._formatError (/srv/node_modules/nodemailer/lib/smtp-connection/index.js:777:19)
at SMTPConnection._actionMAIL (/srv/node_modules/nodemailer/lib/smtp-connection/index.js:1546:34)
at SMTPConnection._responseActions.push.str (/srv/node_modules/nodemailer/lib/smtp-connection/index.js:1028:18)
at SMTPConnection._processResponse (/srv/node_modules/nodemailer/lib/smtp-connection/index.js:935:20)
at SMTPConnection._onData (/srv/node_modules/nodemailer/lib/smtp-connection/index.js:742:14)
at TLSSocket.SMTPConnection._onSocketData.chunk (/srv/node_modules/nodemailer/lib/smtp-connection/index.js:195:44)
at emitOne (events.js:116:13)
at TLSSocket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
at TLSSocket.Readable.push (_stream_readable.js:208:10)
at TLSWrap.onread (net.js:601:20)
code: 'EENVELOPE',
response: '530 5.5.1 Authentication Required.',
responseCode: 530,
command: 'MAIL FROM' }
The error is pretty clear: Failed Auth but it's strange since the test worked earlier!
Connection parameters are:
// options to connect to server
const smtpOptions = {
host: 'smtp.zoho.eu',
port: 465,
secure: true,
auth: {
user: functions.config().nodemailer.user,
pass: functions.config().nodemailer.pass
}
};
// transporter for sending the email
const transporter = nodeMail.createTransport( smtpOptions );
Thank you guys in advance
transporter.verify only tests the connection and authentication, it looks like the that you are not authorised to use the particular MAIL FROM address.

Nodemailer whit GMail SMTP OAuth2 autentication is getting me 'Invalid status code 401'

I'm trying to make a simple mail sender using Nodemailer 3, the GMail API whit OAuth2 autentication.
Here's my script:
var serverConfig = {
gmail: {
client_user : 'my#email.com',
client_id : '349...myClientId',
secret : 'mysecret..123jd123',
refresh_token : 'x/xxxxxxxxxxxxxx-reZuEMeSuJaSERmCVY',
access_token : 'xxxxxxxxxxxxxxxxx',
expires: '3599'
}
}
// 3LO authentication https://nodemailer.com/smtp/oauth2/#example-3
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
type: 'OAuth2',
user: serverConfig.gmail.client_user,
clientId: serverConfig.gmail.client_id,
clientSecret: serverConfig.gmail.secret,
refreshToken: serverConfig.gmail.refresh_token
},
});
module.exports = {
"send": function(_from,_to,_subject,_html,_text){
// setup email data with unicode symbols
var mailOptions = {
from: _from,
to: _to, // list of receivers
subject: _subject, // Subject line
html: _html, // html body
text: _text // plain text body
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
return console.log(error);
}
console.log('Message ' + info.messageId + ' sent: %s' + info.response);
})
}
}
When I force the access_token in the auth object, the email is sent without any problem. But, when I don't specify the access_token, only de refresh_token, I'm getting this error:
{ Error: Invalid status code 401
at ClientRequest.req.on.res (/myproject/node_modules/nodemailer/lib/fetch/index.js:193:23)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:474:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
at TLSSocket.socketOnData (_http_client.js:363:20)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at TLSSocket.Readable.push (_stream_readable.js:134:10)
type: 'FETCH',
sourceUrl: 'https://accounts.google.com/o/oauth2/token',
code: 'EAUTH',
command: 'AUTH XOAUTH2' }
Maybe it's too late, but just answering here incase someone comes across the same issue. My problem rectified when the refreshToken was reset. This article gives great instructions for the whole process
I was able to fix this by going to https://console.cloud.google.com/apis/credentials, selecting the correct OAuth 2.0 Client ID, and choosing "Reset Secret" at the top. This revoked my old secret and generated a new one, which I then used in the OAuth Playground to exchange for a refresh token. I put the new Client Secret and Refresh Token in the auth object for nodemailer and it started working again.

Resources