Unable to send email through nodemailer - node.js

I'm developing node.js application in localhost. In this I'm trying to send mail using nodemailer.
Here is the code to used to send mail:
const nodemailer = require('nodemailer');
module.exports = {
sendMail : function( message, htmlMessage, subject, email ) {
const transporter = nodemailer.createTransport( {
service : 'gmail',
host : 'smtp.gmail.com',
auth : {
user : 'username',
pass : 'password'
},
tls: {
rejectUnauthorized: false
}
});
// setup email data with unicode symbols
let mailOptions = {
from : 'sender mail id', // sender address
to : email, // list of receivers
subject : subject, // Subject line
text : message, // plain text body
html : htmlMessage // html body
};
// send mail with defined transport object
transporter.sendMail( mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
});
}
};
I'm getting the below error:
Error: connect ETIMEDOUT 74.125.130.108:587
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
errno: -4039,
code: 'ESOCKET',
syscall: 'connect',
address: '74.125.130.108',
port: 587,
command: 'CONN'
}
Kindly someone help me to resolve this issue.

If your firewall is already turned off, you should make these changes.
const nodemailer = require('nodemailer');
module.exports = {
sendMail : function( message, htmlMessage, subject, email ) {
const transporter = nodemailer.createTransport({
service : 'gmail',
auth : {
user : 'username',
pass : 'password'
}
});
// setup email data with unicode symbols
let mailOptions = {
from : 'xyz#gmail.com', // sender address
to : email, // list of receivers
subject : subject, // Subject line
text : message, // plain text body
};
// send mail with defined transport object
transporter.sendMail( mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
});
}
};
Once you setup, open the link https://myaccount.google.com/lesssecureapps and turn 'ON' Allow less secure apps: ON. And then check by running your node server.

Related

nodemailer error, getting : Invalid login: 451 4.7.0 Temporary server error. Please try again later.(researched, limited resources on stackoverflow)

After checking similar posts online, still couldn't figure out the issue. I am trying to send email through nodemailer by using my outlook business email. I am getting this error message that I couldn't fix.
Here is error message:
Error: Invalid login: 451 4.7.0 Temporary server error. Please try again later. PRX4 [BY3PR10CA0026.namprd10.prod.outlook.com]
at SMTPConnection._formatError (/Users/zhongzechen/Hello--website--backend/node_modules/nodemailer/lib/smtp-connection/index.js:774:19)
at SMTPConnection._actionAUTHComplete (/Users/zhongzechen/Hello--website--backend/node_modules/nodemailer/lib/smtp-connection/index.js:1518:34)
at SMTPConnection.<anonymous> (/Users/zhongzechen/Hello--website--backend/node_modules/nodemailer/lib/smtp-connection/index.js:1476:18)
at SMTPConnection._processResponse (/Users/zhongzechen/Hello--website--backend/node_modules/nodemailer/lib/smtp-connection/index.js:937:20)
at SMTPConnection._onData (/Users/zhongzechen/Hello--website--backend/node_modules/nodemailer/lib/smtp-connection/index.js:739:14)
at TLSSocket.SMTPConnection._onSocketData (/Users/zhongzechen/Hello--website--backend/node_modules/nodemailer/lib/smtp-connection/index.js:189:44)
Tried adding tls to { ciphers: 'SSLv3' }, didn;t work out.
Here is part of my code:
const output = `<h3>Hello</h3>`;
let transporter = nodemailer.createTransport({
host: "smtp-mail.outlook.com",
secure: false,
port: 587,
auth:{
user:"myoutlookemail",
pass:"mypassword"
}
})
let mailOptions ={
from:'myoutlookemail',
to:req.body.email,
subject:"Hello there",
text:"Hello there",
html:output
}
transporter.sendMail(mailOptions,(error,info)=>{
if(error){
console.log('*********ERROR IS HAPPENING*************')
return console.log(error);
}
console.log('Message Sent~~~~~~~~~~~~~~~: %s',info.response);
//console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
});
Try this
Edit as required
const nodemailer = require("nodemailer");
const transporter = nodemailer.createTransport({
service: 'service_provider',
auth: {
user: 'email',
pass: 'password'
}
});
const mailOptions = {
from: 'email',
to: req.body.email,
subject: 'Protocol 5416',
text: "Anything"
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});

Unable to send email through node js, tried few methods

var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
secureConnection: false,
port: 587,
tls: {
ciphers: 'SSLv3'
},
requireTLS: true,
auth: {
user: 'mygmail',
pass: 'mypass'
}
});
var mailOptions = {
from: 'mygmail',
to: 'receiver gmail',
subject: 'Sending Email using Nodemailer',
text: 'That was easy!'
};
transporter.sendMail(mailOptions, (error, info) => {
if (error)
return console.log(error);
console.log('Email sent: ' + info.response);
});
Above is my code for sending email through node js but I keep encounter a timeout error as below
{ Error: connect ETIMEDOUT 74.125.24.109:587
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1191:14)
errno: 'ETIMEDOUT',
code: 'ECONNECTION',
syscall: 'connect',
address: '74.125.24.109',
port: 587,
command: 'CONN' }
I also tried another basic way as for the following link: https://www.w3schools.com/nodejs/nodejs_email.asp but it is not working as well.
I've already turned on allow the less secure app on my google account.
Beside of that, I also tried the method like the one in the following the link: https://jsfiddle.net/burawi/1u9m2mou/ and it is still unable to work, I generated all the client_id, client_secret, access_token, and refresh_token.
Does anyone have any latest guide or solution for sending email through node js?
Thanks
This is a network restriction issue.
Please try the same thing in your mobile network and it will work.
router.get('/mailTest', (req, res) => {
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: "mrmanagementbbsr#gmail.com", // generated ethereal user
pass: "Test#123" // generated ethereal password
}
});
let mailOptions = {
from: "mrmanagementbbsr#gmail.com", // sender address
to: 'nsubhadipta#gmail.com', // list of receivers
subject: "test subject", // Subject line
text: 'demo text'
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
res.json({ status: -1, message: 'Error Occured', error: error });
}
else {
res.json({ status: 1, message: "Email Sent" });
}
});
});
Ensure you turn on your Less secure app access, else your emails will not go through.
Then you might want to try this example:
{
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'mymail',
pass: 'mypass'
}
});
let mailOptions = {
from: 'mygmail',
to: 'receiver gmail',
subject: 'Sending Email using Nodemailer',
text: 'That was easy!'
};
transporter.sendMail(mailOptions, (error, info)=>{
if (error) {
console.log(error);
} else {
console.log('Email sent ' + info.response');
}
});
res.json({success: 'whatever message you plan on writing'});
}

Error when sending email using nodemailer / smtp.gmail.com

I'm trying to set up nodemailer for an app. I'm receiving an error when I try it.
This is my setup:
email = setting.email;
password = setting.password;
var transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: '***********#gmail.com', // real email
pass: '*********' // real password
}});
// var transporter = nodemailer.createTransport({
// service: 'gmail',
// auth: {
// user: email, // Your email id
// pass: password // Your password
// }
// });
var mailOptions = {// sender address
from: email,
to: to, // list of receivers
subject: sub, // Subject line
text: text, //, /// plaintext body
html: html
}
//console.log(JSON.stringify(mailOptions));
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.error(error);
} else {
console.log(info.response);
}
;
});
});
} catch (error) {
console.error(error);
}
This is the first time I've tried using nodemailer. I am using real email and password. The error are:
(node:18974) [DEP0025] DeprecationWarning: sys is deprecated. Use util
instead. Magic happens on port 5000 ERROR! ERROR! ERROR! ERROR!
provider_analytic_daily saved. { Error: Connection timeout
at SMTPConnection._formatError (/root/faszz/node_modules/smtp-connection/lib/smtp-connection.js:528:15)
at SMTPConnection._onError (/root/faszz/node_modules/smtp-connection/lib/smtp-connection.js:514:16)
at SMTPConnection. (/root/faszz/node_modules/smtp-connection/lib/smtp-connection.js:236:14)
at ontimeout (timers.js:498:11)
at tryOnTimeout (timers.js:323:5)
at Timer.listOnTimeout (timers.js:290:5) code: 'ETIMEDOUT', command: 'CONN' }
functionObj = {};
functionsObj.getSmtpTransport = function() {
var smtpTransport = nodemailer.createTransport({
service: "Gmail",
auth: {
user: "<your email address>",
pass: "<your pass>"
}
});
return smtpTransport;
}
functionsObj.sendMailForPasswordReset = function(to, token) {
var smtpTransport = functionsObj.getSmtpTransport();
var mailOptions = {
to: to,
subject: "Blabla.com Reset Password",
html: "Hi,<br> Click to link for resetting password.<br><a href='https://<blabla.com>/reset/" + urlencode(token) + "'>Click Me !!!</a>"
}
smtpTransport.sendMail(mailOptions, function(error, response) {
if (error) {
return error;
}
else {
return true;
}
});
};
Hi,
The code above worked in my project without any error. But you should allow to third party softwares to use your google account from google.
Here the google's support page for this case:
https://support.google.com/accounts/answer/6010255?hl=en
I recommend that all input should be validated :) For example if you are taking "to" parameter from user. You should validate "to" parameter is a valid email address ?

Node.js Nodemailer Failed to Send Email

I'm unable to send an email in Node.js using Nodemailer. I don't know how to debug it simply because I don't understand the reply from the terminal. I think it is a SSL issue, but as you can see, I've set 'secure' as 'true', so I really don't know where should I start to debug it.
Source Code:
var nodemailer = require('nodemailer');
var mailOptions = {
host: "smtp.mail.me.com",
port: 587,
secure: true,
auth: {
user: "***",
pass: "***"
}
};
var transporter = nodemailer.createTransport(mailOptions);
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
Result from terminal:
{ Error: 140736043987904:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:../deps/openssl/openssl/ssl/s23_clnt.c:827:
code: 'ECONNECTION', command: 'CONN' }
You are using your transport details to send an email. More information can be found https://nodemailer.com/about/.
let mailOptions = {
from: '"Fred Foo 👻" <foo#example.com>', // sender address
to: 'bar#example.com, baz#example.com', // list of receivers
subject: 'Hello ✔', // Subject line
text: 'Hello world?', // plain text body
html: '<b>Hello world?</b>' // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
// Preview only available when sending through an Ethereal account
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321#example.com>
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
});

send email via nodemailer

I try to send email via nodemailer but getting error - TypeError: Cannot read property 'method' of undefined. It looks like sendMail function is not defined. Any advise please?
P.S. This code for chatbot hosted on AWS
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
module.exports = function someName() {
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport(smtpTransport({
service: 'gmail',
auth: {
user: '7384093#gmail.com',
pass: '*******'
}
}))
// setup e-mail data with unicode symbols
var mailOptions = {
from: '"nerd studio" <7384093#gmail.com>', // sender address
to: '7384093#gmail.com', // list of receivers
subject: 'Подтверждение запроса \\ разработак чат-ботов \\ nerd studio', // Subject line
text: 'Добрый день! Вы оставили нашему Валере запрос и мы с радостью подтверждаем его получение. В ближайшее время с вами свяжется наш менелдер', // plaintext body
html: '<b>Добрый день! Вы оставили нашему Валере запрос и мы с радостью подтверждаем его получение. В ближайшее время с вами свяжется наш менелдер</b>' // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
console.log(mailOptions);
console.log(info);
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
}
You don't need to install npm nodemailer-smtp-transport, only nodemailer is enough to send email to gmail. But first, go to the https://myaccount.google.com/security google account and scroll down and check Allow less secure apps: ON and keep ON. you will send your gmail email. Here, is the full code -
var nodemailer = require('nodemailer');
app.post('/contactform', function (req, res) {
var mailOpts, smtpTrans;
//Setup Nodemailer transport, I chose gmail. Create an application-specific password to avoid problems.
smtpTrans = nodemailer.createTransport(smtpTransport({
service: 'gmail',
// host:'smtp.gmail.com',
// port:465,
// secure:true,
auth: {
user: "xxxxxx#gmail.com",
pass: "xxxxxx"
}
}));
var mailoutput = "<html>\n\
<body>\n\
<table>\n\
<tr>\n\
<td>Name: </td>" + req.body.form_name + "<td></td>\n\
</tr>\n\
<tr>\n\
<td>Email: </td><td>" + req.body.form_email + "</td>\n\
</tr>\n\
<tr>\n\
<td>MN: </td>" + req.body.form_phone + "<td></td>\n\
</tr>\n\
<tr>\n\
<td>Messge: </td>" + req.body.form_message + "<td></td>\n\
</tr>\n\
</table></body></html>";
//Mail options
mailOpts = {
to: "Your_App_Name <xxxxxxxx#gmail.com>",
subject: req.body.form_subject,
html: mailoutput
};
smtpTrans.sendMail(mailOpts, function (error, res) {
if (error) {
// res.send("Email could not send due to error" +error);
return console.log(error);
}
});
console.log('Message sent successfully!');
res.render('contact.ejs');
});
//console.log(query.sql);
});
I have nodemailer currently working this way: Create a file config/mail.js:
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
host: 'yourHost',
port: 2525, //example
auth: {
user: 'yourUser',
pass: 'yourPass'
}
});
module.exports = function(params) {
this.from = 'yourEmail';
this.send = function(){
var options = {
from : this.from,
to : params.to,
subject : params.subject,
text : params.message
};
transporter.sendMail(options, function(err, suc){
err ? params.errorCallback(err) : params.successCallback(suc);
});
}
}
And then, anytime I want to send an email:
var Mail = require(path.join(__dirname, '..', '..', 'config', 'mail.js'));
var options = {
to: 'example#example.com',
subject: 'subject',
message: 'your message goes here'
}
var mail = new Mail({
to: options.to,
subject: options.subject,
message: options.message,
successCallback: function(suc) {
console.log('success');
},
errorCallback: function(err) {
console.log('error: ' + err);
}
});
mail.send();
Try this code.First you have to create an app in Google Cloud Console and Enable Gmail API from library.Get the credentials of your app.For that click on Credentials and in the place of Authorized redirect URIskeep this link https://developers.google.com/oauthplayground and save it.Next in another tab open this link https://developers.google.com/oauthplayground/ click on settings symbol on right side.And make a tick on check box(i.e,Use your own OAuth credentials) after this You have to give your clientId and clientSecret.And at the sametime on left side there is a text box with placeholder like Input Your Own Scopes there keep this link https://mail.google.com/
and click on Authorize APIs then click on Exchange authorization code for tokens then you will get your refreshToken and accessToken keep these two in your code.Hope this hepls for you.
const nodemailer=require('nodemailer');
const xoauth2=require('xoauth2');
var transporter=nodemailer.createTransport({
service:'gmail',
auth:{
type: 'OAuth2',
user:'Your_Email',
clientId:'Your_clientId',//get this from Google Cloud Console
clientSecret:'Your_clientSecret',
refreshToken:'Your_refreshToken',//get this from https://developers.google.com/oauthplayground/
accessToken:'Your_accessToken'
},
});
var mailOptions={
from:'<Your_email>',
to:'Your firends mail',
subject:'Sample mail',
text:'Hello !!!!!!!!!!!!!'
}
transporter.sendMail(mailOptions,function(err,res){
if(err){
console.log('Error');
}
else{
console.log('Email Sent');
}
})
I find solution for ,
How to send email from="userEmail" to="myEmail"?
THIS IS TRICK
var nodemailer = require('nodemailer'); router.post('/contacts-variant-2', (req, res, next) => { var name=req.body.name; var email=req.body.email; var message=req.body.message; const output=`
<h3>Contact Details</h3>
<ul>
<li>Name is : ${req.body.name}</li>
<li>Email is : ${req.body.email}</li>
</ul>
<h3>Message</h3>
<p>${req.body.message}</p>
`; var transporter = nodemailer.createTransport({ service: 'yahoo', auth: { user: 'create_new_email#yahoo.com', pass: 'password' } }); var mailOptions = { from:'create_new_email#yahoo.com', to:'myFriend#gmail.com', subject: name, text: 'Your have a new
contact request', html:output }; transporter.sendMail(mailOptions, function(error, info){ if (error) { console.log("errors is somthing "+error); res.send(404); } else { console.log('Email sent: ' + info.response); res.send(200); } }); });
Using Gmail
var nodemailer = require('nodemailer');
// Create the transporter with the required configuration for Gmail
// change the user and pass !
var transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true, // use SSL
auth: {
user: 'myemail#gmail.com',
pass: 'myPassword'
}
});
// setup e-mail data
var mailOptions = {
from: '"Our Code World " <myemail#gmail.com>', // sender address (who sends)
to: 'mymail#mail.com, mymail2#mail.com', // list of receivers (who receives)
subject: 'Hello', // Subject line
text: 'Hello world ', // plaintext body
html: '<b>Hello world </b><br> This is the first email sent with Nodemailer in Node.js' // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
Using Hotmail
var nodemailer = require('nodemailer');
// Create the transporter with the required configuration for Outlook
// change the user and pass !
var transporter = nodemailer.createTransport({
host: "smtp-mail.outlook.com", // hostname
secureConnection: false, // TLS requires secureConnection to be false
port: 587, // port for secure SMTP
tls: {
ciphers:'SSLv3'
},
auth: {
user: 'mymail#outlook.com',
pass: 'myPassword'
}
});
// setup e-mail data, even with unicode symbols
var mailOptions = {
from: '"Our Code World " <mymail#outlook.com>', // sender address (who sends)
to: 'mymail#mail.com, mymail2#mail.com', // list of receivers (who receives)
subject: 'Hello ', // Subject line
text: 'Hello world ', // plaintext body
html: '<b>Hello world </b><br> This is the first email sent with Nodemailer in Node.js' // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
Alternatively, if your account is hotmail instead of outlook, you can use the buil-in hotmail service using the following transport:
var transport = nodemailer.createTransport("SMTP", {
service: "hotmail",
auth: {
user: "user#hotmail.com",
pass: "password"
}
});
Using Zoho
var nodemailer = require('nodemailer');
// Create the transporter with the required configuration for Gmail
// change the user and pass !
var transporter = nodemailer.createTransport({
host: 'smtp.zoho.com',
port: 465,
secure: true, // use SSL
auth: {
user: 'myzoho#zoho.com',
pass: 'myPassword'
}
});
// setup e-mail data, even with unicode symbols
var mailOptions = {
from: '"Our Code World " <myzoho#zoho.com>', // sender address (who sends)
to: 'mymail#mail.com, mymail2#mail.com', // list of receivers (who receives)
subject: 'Hello ', // Subject line
text: 'Hello world ', // plaintext body
html: '<b>Hello world </b><br> This is the first email sent with Nodemailer in Node.js' // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});

Resources