unable to send mail using nodemailer node.js api? - node.js

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.

Related

Nodemailer to GMAIL Error: self-signed certificate in certificate chain

It is a GMAIL server my two-step password is correct and my recipient data is correct
"use strict";
const nodemailer = require("nodemailer");
// async..await is not allowed in global scope, must use a wrapper
async function main() {
// 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();
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: "smtp.gmail.com", //Servidor de gmail
port: 465, //Puerto de servidor de gmail
secure: true, //Esta activado en true // true for 465, false for other ports
auth: {
user: ' ****#gmail.com',/*testAccount.user,*/ // generated ethereal user
pass: 'qskafnvgyhzyrceb'/*testAccount.pass,*/ // generated ethereal password
},
});
// send mail with defined transport object
let info = await transporter.sendMail({
from: '*****#gmail.com',/*'"Fred Foo 👻" <foo#example.com>',*/ // sender address
to: '*****#gmail.com',/*"bar#example.com, baz#example.com",*/ // list of receivers
subject: "Hello ✔", // Subject line
text: "Hello world?", // plain text body
html: "<h1>Hello World</h1>", // html body
});
}
main().then(() => { console.log('Correo Enviado') }).catch((err)=>{ console.log(err) }/*console.error*/);`
but I have this error
Error: self-signed certificate in certificate chain
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: 'ESOCKET',
command: 'CONN'
}
I want send any email to gmail acount,
this code worked for me last week

could not setup dkim in nodemailer

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.

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

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

How to send mail with nodemailer (node.js) by direct method?

I try to write simple mailer just to send some text (for testing purposes) with nodemailer. If I understood well it may sent a mail by smtp or direct. At first I want to sent with DIRECT method.
The next code very simple:
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({direct:true,
host: 'smtp.yandex.ru',
port: 465,
auth: {
user: 'login#yandex.ru',
pass: 'password' },
secure: true
});
var mailOptions = {
from: 'nworksheet#gmail.com',
to: 'sky-bell#mail.ru',
subject: 'Hello',
text: 'This is auto mail sending'
};
transporter.sendMail(mailOptions, function (error, info) {
if(error) {
return console.log(error);
}
console.log("Message sent "+info.response)
});
But I have the next error:
{ Error: Sending failed
at QueryReqWrap.asyncCallback [as callback] (dns.js:65:16)
at QueryReqWrap.onresolve [as oncomplete] (dns.js:216:10)
errors:
[ { Error: queryMx ENOTFOUND mail.ru
at errnoException (dns.js:28:10)
at QueryReqWrap.onresolve [as oncomplete] (dns.js:216:19)
code: 'ENOTFOUND',
errno: 'ENOTFOUND',
syscall: 'queryMx',
hostname: 'mail.ru' } ] }
What does it mean? How to fix it? Node not see 'mail.ru'? Why?
The best way to achieve this is
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'Yandex',
auth: {
user: 'your_yandex_email',
pass: 'your_password_for_email' },
});
var mailOptions = {
from: 'your_yandex_email',
to: 'sky-bell#mail.ru',
subject: 'Hello',
text: 'This is auto mail sending'
};
transporter.sendMail(mailOptions, function (error, info) {
if(error) {
return console.log(error);
}
console.log("Message sent "+info.response)
});
Whenever you specify the service command, it automatically sets the port and secures the email.
Also remember to put and fetch the credentials from a config file.
Looks like it can't find an MX record for mail.ru. It seems to exist however. https://toolbox.googleapps.com/apps/dig/#MX/mail.ru
Does this machine have DNS set up properly? Can you dig it from that machine?

Resources