could not setup dkim in nodemailer - node.js

I want to setup DKIM in nodemailer. Without DKIM, tls and "secure: true" my code works fine however, when I run code changed for DKIM it shows error:
Code:
var nodemailer = require('nodemailer');
var fs = require("fs");
const pr_key = fs.readFileSync("private.key", {encoding: "utf-8"})
const transporter = nodemailer.createTransport({
port: 465, // Postfix uses port 25
host: 'example.com',
secureConnection: false,
tls: {
ciphers:'SSLv3'
// rejectUnauthorized: false
},
secure: true,
dkim: {
domainName: "mail.example.com",
keySelector: "mail",
privateKey: pr_key
},
auth: {
user: "abc",
pass: "def"
},
});
var message = {
from: 'noreply#example.com',
to: 'pleasereply#example.com',
subject: 'Confirm Email',
text: 'Please confirm your email',
html: '<p>Please confirm your email</p>'
};
transporter.sendMail(message, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
});
Error Message:
[Error: 7336:error:1408F10B:SSL routines:ssl3_get_record:wrong version
number:c:\ws\deps\openssl\openssl\ssl\record\ssl3_record.c:332: ] {
library: 'SSL routines', function: 'ssl3_get_record', reason:
'wrong version number', code: 'ESOCKET', command: 'CONN' }
I have already configured TXT record for DKIM in DNS and SMTP server running on my server side is programed using library "smtp-server" module of nodejs.
What I tried:
I tried changing port to 25, 2525, 465 and 143
Tried every combination of host, domainname for domain "example.com" and tried keySelector "mail" and "#".
I tried commenting "secureConnection" and "tls: {}" and then changing to "secure: false" which results in other error:
Error: self signed certificate
at TLSSocket.onConnectSecure (node:_tls_wrap:1530:34)
at TLSSocket.emit (node:events:526:28)
at TLSSocket._finishInit (node:_tls_wrap:944:8)
at TLSWrap.ssl.onhandshakedone (node:_tls_wrap:725:12) { code: 'ESOCKET', command: 'CONN' }
i tried to change "to:" property of message object to my gmail account just for testing but still got same message saying I got wrong version
Help me resolving this issue.

Related

Error: connect ECONNREFUSED Nodemailer Ethereal

I have an error when trying to use the example from nodemailer.
I modified it a little bit but it has all of the same core. When I try to run it I get this error:
Error: connect ECONNREFUSED 13.49.22.0:587
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1161:16) {
errno: -111,
code: 'ESOCKET',
syscall: 'connect',
address: '13.49.22.0',
port: 587,
command: 'CONN'
}
I have searched and I can't find any answers about this. I have heard that downgrading nodemailer's version to 4.7.0 fixes it but I have not tested this yet.
I also tested this connection to google, but it didn't work.
The function that is actually run is this:
async function nodeMailerMain() {
// Generate test SMTP service account from ethereal.email
// Only needed if you don't have a real mail account for testing
let testAccount = await nodemailer.createTestAccount().catch((err) => console.log(err))
// create reusable transporter object using the default SMTP transport
let transporter = await nodemailer.createTransport({
host: testAccount.smtp.host,
port: testAccount.smtp.port,
secure: testAccount.smtp.secure, // true for 465, false for other ports
auth: {
user: testAccount.user, // generated ethereal user
pass: testAccount.pass, // generated ethereal password
},
})//.catch((err) => console.log(err))
console.log(testAccount.smtp.host);
console.log("successfully created transporter");
let message = {
from: 'Sender Name <sender#example.com>',
to: 'Recipient <recipient#example.com>',
subject: 'Nodemailer is unicode friendly ✔',
text: 'Hello to myself!',
html: '<p><b>Hello</b> to myself!</p>'
};
// send mail with defined transport object
transporter.sendMail(message, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Email sent: ' + info.response);
console.log("Message sent: %s", info.messageId);
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321#example.com>
// Preview only available when sending through an Ethereal account
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
});
}
It turns out that, since I was using a Gitpod workspace, the email functionality had been blocked to avoid spam-bots. See this issue on Github for more information: https://github.com/gitpod-io/gitpod/issues/8976

unable to send mail using nodemailer node.js api?

I have written code to send gmail using nodemailer node.js rest api. this is working fine for my local system server but when the same code i deployed on windows-2000 server, i am unable to send gmail and getting internal server error.
this is the code snippet i am using --
var nodemailer = require('nodemailer');
var stringify = require('json-stringify');
// create reusable transport method (opens pool of SMTP connections)
var smtpTransport = nodemailer.createTransport({
service: 'Gmail',
host: 'smtp.gmail.com',
port:587,
secure: false,
auth: {
user: 'user#gmail.com',
pass: 'user#123'
}
});
// setup e-mail data with unicode symbols
module.exports={
create:function(req,res){
var params=req.allParams();
var order_details=JSON.stringify(params);
//console.log("order-->"+order_details);
var mailOptions = {
from: 'user#gmail.com', // sender address
to: 'user1#gmail.com', // list of receivers
subject: "g-mail message ", // Subject line
html: order_details // html body
}
console.log("mailOptions"+JSON.stringify(mailOptions));
smtpTransport.sendMail(mailOptions, function(err, result){
console.log(result);
if(err){
return res.status(500).json("Error");
//return res.json("System Error")
}else{
return res.status(200).json("e-mail sent to customer");
}
smtpTransport.close();
});
}
}
when i am calling the api from local system server this is the response i am getting for conole.log(result)-->
{ accepted: [ 'user1#gmail.com' ],
rejected: [],
envelopeTime: 1094,
messageTime: 1124,
messageSize: 300,
response: '250 2.0.0 OK 1539452574 189-v6sm7035924pfe.121 - gsmtp',
envelope:
{ from: 'user#gmail.com',
to: [ 'user1#gmail.com' ] },
messageId: '<d84e7c1e-7158-5c6a-851d-a783e05be5ce#gmail.com>' }
but when i am trying to call the api from my windows-2000 server, for line console.log(result)--> i am getting "undefined".
So my question is whether i am getting this response from gmail.smtp server or gmail.smtp server is unreachable from the system.
I tried to ping gmail.smtp server from my windws-2000 server and there is 0% packet loss. so gmail.smtp is reachable from my server?
I also tried port 465,587,25 and secure- true, false option.
for Error log i am getting this-
{ Error: self signed certificate in certificate chain at TLSSocket.
<anonymous> (_tls_wrap.js:1105:38) at emitNone (events.js:106:13)
at TLSSocket.emit (events.js:208:7) at TLSSocket._finishInit (_tls_wrap.js:639:8) at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:469:38) code: 'ECONNECTION', command: 'CONN' }}
Thnaks for your's valuable inputs on this issue.
var nodemailer = require('nodemailer');
var stringify = require('json-stringify');
// add this line before nodemailer.createTransport()
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
// create reusable transport method (opens pool of SMTP connections)
var smtpTransport = nodemailer.createTransport({
service: 'Gmail',
host: 'smtp.gmail.com',
port:587,
secure: false,
auth: {
user: 'user#gmail.com',
pass: 'user#123'
}
});
now it will work.

Why am I getting an NodeMailer HELO 501 hostname error?

I am getting an NodeMailer error when I try to connect to my NodeMailer SMTP server (which happens to be on the same machine):
error: { Error: Invalid HELO. response=501 Error: Syntax: HELO hostname: 501 Error: Syntax: HELO hostname
at SMTPConnection._actionHELO (/home/hunter/projects/proxy-e/node_modules/nodemailer/lib/smtp-connection/index.js:1139:27)
at SMTPConnection._processResponse (/home/hunter/projects/proxy-e/node_modules/nodemailer/lib/smtp-connection/index.js:762:20)
at SMTPConnection._onData (/home/hunter/projects/proxy-e/node_modules/nodemailer/lib/smtp-connection/index.js:558:14)
at TLSSocket._socket.on.chunk (/home/hunter/projects/proxy-e/node_modules/nodemailer/lib/smtp-connection/index.js:510:47)
at TLSSocket.emit (events.js:182:13)
at addChunk (_stream_readable.js:283:12)
at readableAddChunk (_stream_readable.js:264:11)
at TLSSocket.Readable.push (_stream_readable.js:219:10)
at TLSWrap.onread (net.js:639:20)
code: 'EPROTOCOL',
response: '501 Error: Syntax: HELO hostname',
responseCode: 501,
command: 'HELO' }
I am attempting to connect via:
let optionsTwo = {
port: 465,
host: 'mydomain.com',
secure: true,
name: 'mydomain.com',
transactionLog: true,
debug: true,
};
const connection = new SMTPConnection(optionsTwo);
connection.connect(function() {
console.log("connected?");
let authTwo = {
user: 'foo',
pass: 'bar'
};
connection.login(authTwo, function(err) {
if (err) {
console.log("err::", err);
}
console.log("logged in?");
});
});
connection.on("error", function(err) {
console.log("error: ", err);
});
My NodeMailer server:
let options = {
secure: false,
authOptional: false,
secure: true,
key: hskey,
cert: hscert,
ca: [hschain],
onAuth(auth, session, callback) {
...
},
}
const emailServer = new SMTPServer(options);
emailServer.listen(465);
My server has a registered domain name and a certificate from LetsEncrypt. I haven't been able to figure out why I continue to get this HELO hostname 501 error. From digging into the NodeMailer JS files I found this:
Handles server response for STARTTLS command. If there's an error
* try HELO instead, otherwise initiate TLS upgrade. If the upgrade
* succeedes restart the EHLO
Which makes me assume that STARTTLS has some sort of error so it's attempting to use HELO and failing, but why?
For some reason name: 'mydomain.com', is incorrect, and when removing it, I no longer get the error.

NodeJs Error When Submitting Email using Nodemailer

I have followed these steps to setup nodemailer
1) Allow access to less secure apps in gmail
2) Written the following in app.js
app.post('/reachus/send',function(req,res){
var transporter=nodemailer.createTransport({
service:'Gmail',
auth: {
user:'my#gmail.com',
pass:'***'
}
});
var mailOptions={
from:'Naveen DK <my#gmail.com>',
to:'my#gmail.com',
subject:'Email Sent from your website',
text:'You have a submission with the following details.. Name: '+req.body.name +'Email: '+req.body.email+' Message: '+ req.body.message,
html: '<p>You have a submission with the following details..</p><ul><li> Name :'+req.body.name + ' </li><li>Email: '+req.body.email +'</li><li>Message ' + req.body.message +'</li></ul>'
};
transporter.sendMail(mailOptions,function(error,info){
if(error){
console.log(error);
res.redirect('/');
} else{
console.log('Message Sent ' + info.response);
res.redirect('/');
}
});
});
3) Once I Click on Submit Email I get the following error
{ Error: read ECONNRESET
at exports._errnoException (util.js:1026:11)
at TLSWrap.onread (net.js:569:26)
code: 'ECONNECTION',
errno: 'ECONNRESET',
syscall: 'read',
command: 'CONN
}
Please find the below 2 vids for more details
1 https://www.dropbox.com/s/nc1zvivlfpabj6h/HowMyCodeLooksLike.wmv?dl=0
2 https://www.dropbox.com/s/tfsqu6ir90s682h/ErrorOnceSubmissionDone.wmv?dl=0
Thanks in advance
Naveen
use below code for sending email from nodemailer, inside function pass ur parameter and you will get ur result.
var AppConfig = {
'sendEmailID': 'useremail',
'sendEmailFromName': 'senderemail',
'sendEmailPassword': 'password'
}
function SendEmail(toEmail, Subject, html) {
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: '587',
auth: {
user: "username",
pass: AppConfig.sendEmailPassword
},
secureConnection: 'false',
tls: {
ciphers: 'SSLv3'
}
});
// setup e-mail data with unicode symbols
var mailOptions = {
from: AppConfig.sendEmailFromName, // sender address
to: toEmail, // list of receivers
subject: Subject, // Subject line
html: html // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
return console.log("ERROR----" + error);
}
console.log('Message sent: ' + info.response);
});
}
With the response I got from #chetan mekha I changed my code as follows:
var smtpTransport=nodemailer.createTransport({
host: 'smtp.gmail.com',
port: '587',
auth: {
user: "**",
pass: "**"
},
secureConnection: 'false',
tls: {
ciphers: 'SSLv3'
}
});
But there another error came up saying : { [Error: self signed certificate in certificate chain] code: 'ECONNECTION', command: 'CONN' } But adding the line
rejectUnauthorized: false under ciphers made it work! so final code snippet that worked for me looks like this..
var smtpTransport=nodemailer.createTransport({
host: 'smtp.gmail.com',
port: '587',
auth: {
user: "**",
pass: "**"
},
secureConnection: 'false',
tls: {
ciphers: 'SSLv3',
rejectUnauthorized: false
}
});

Connection timeout error when sending mail from Zohomail using Nodemailer

Below is my Node app.js code. With these settings, I am receiving a connection timeout error. Any idea what I am missing here?
var nodemailer = require("nodemailer");
var transporter = nodemailer.createTransport({
host: 'smtp.zoho.com',
port: 465,
secure: true, // use SSL
auth: {
user: '<myemail#example.com>',
pass: '<myemailpassword>'
}
});
var mailOptions = {
from: "<fromemail#example.com>",
to: "<toemail#example.com>",
subject: "Hello",
generateTextFromHTML: true,
html: { path: './tmpl.html' }
};
transporter.sendMail(mailOptions, function(error, response) {
if (error) {
console.log(error);
} else {
console.log(response);
}
transporter.close();
});
Error shown
{ Error: Connection timeout
at SMTPConnection._formatError (/home/ubuntu/workspace/mailapp/node_modules/nodemailer/lib/smtp-connection/index.js:557:19)
at SMTPConnection._onError (/home/ubuntu/workspace/mailapp/node_modules/nodemailer/lib/smtp-connection/index.js:530:20)
at Timeout._connectionTimeout.setTimeout (/home/ubuntu/workspace/mailapp/node_modules/nodemailer/lib/smtp-connection/index.js:248:18)
at ontimeout (timers.js:380:14)
at tryOnTimeout (timers.js:244:5)
at Timer.listOnTimeout (timers.js:214:5) code: 'ETIMEDOUT', command: 'CONN' }
Can anyone please help me?
Some cloud providers disable ports like 465 and 587, try using port 2525 instead of 465.
Update
Since you're using Cloud9 for this I found out they have blocked all outbound smtp calls from their servers. If you need to send anyways you need to choose another cloud provider or use one of their recommended services.
https://community.c9.io/t/how-can-i-send-email-from-my-app/1262

Resources