send email nodemailer without using gmail smtp - javascript

I have a business email using bell.net email address, and on their site, it says use smtphm.sympatico.ca, as the smtp hostname, as well as port 25 / 587... I have my nodemailer code set up like this:
app.post('/sendBatchEmail', (req, res) => {
var emails = [];
var emailSubject = req.body.emailSubject;
var emailMessage = req.body.emailMessage;
//perform db2 send
var sendEmail = "select * from testEmails"
ibmdb.open(ibmdbconnMaster, function (err, conn) {
if (err) return console.log(err);
conn.query(sendEmail, function (err, rows) {
if (err) {
console.log(err);
}
for (var i = 0; i < rows.length; i++) {
emails.push(rows[i].EMAIL)
}
//send email
async function main() {
let transporter = nodemailer.createTransport({
host: "smtphm.sympatico.ca",
port: 25,
secure: false, // true for 465, false for other ports
auth: {
user: "xxx#bell.net",
pass: "xxx",
},
});
// send mail with defined transport object
let sendBatch = await transporter.sendMail({
from: "my1email#bell.net", // sender address
to: "myemail#gmail.com",
bcc: emails, // list of receivers
subject: emailSubject, // Subject line
text: emailMessage, // plain text body
});
console.log("Message sent: %s", sendBatch.messageId);
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321#example.com>
// Preview only available when sending through an Ethereal account
// console.log("Preview URL: %s", sendBatch.getTestMessageUrl);
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}
main().catch(console.error);
res.redirect("/");
conn.close(function () {
console.log("closed the function app.get(/sendEmailBatch)");
});
});
});
})
however, this doesn't work and gives me this error:
Error: Invalid login: 535 Authentication failed
at SMTPConnection._formatError (/Users/ga/Desktop/PSL/mbs/node_modules/nodemailer/lib/smtp-connection/index.js:774:19)
at SMTPConnection._actionAUTHComplete (/Users/ga/Desktop/PSL/mbs/node_modules/nodemailer/lib/smtp-connection/index.js:1513:34)
at SMTPConnection.<anonymous> (/Users/ga/Desktop/PSL/mbs/node_modules/nodemailer/lib/smtp-connection/index.js:540:26)
at SMTPConnection._processResponse (/Users/ga/Desktop/PSL/mmbs/node_modules/nodemailer/lib/smtp-connection/index.js:932:20)
at SMTPConnection._onData (/Users/ga/Desktop/PSL/mbs/node_modules/nodemailer/lib/smtp-connection/index.js:739:14)
at TLSSocket.SMTPConnection._onSocketData (/Users/ga/Desktop/PSL/mbs/node_modules/nodemailer/lib/smtp-connection/index.js:189:44)
at TLSSocket.emit (events.js:315:20)
at addChunk (internal/streams/readable.js:309:12)
at readableAddChunk (internal/streams/readable.js:284:9)
at TLSSocket.Readable.push (internal/streams/readable.js:223:10) {
code: 'EAUTH',
response: '535 Authentication failed',
responseCode: 535,
command: 'AUTH PLAIN'
}
but works when I change it back to gmail... any ideas?

Related

Client network socket disconnected before secure TLS connection was established when using Node-mailer

Hello guys I'm trying to use this function I wrote ,it was working when I used the free mailer provided by outlook, however this is the error I'm getting
Error: Client network socket disconnected before secure TLS connection
was established
at connResetException (internal/errors.js:609:14)
at TLSSocket.onConnectEnd (_tls_wrap.js:1547:19)
at Object.onceWrapper (events.js:420:28)
at TLSSocket.emit (events.js:326:22)
at endReadableNT (_stream_readable.js:1223:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
{
code: 'ESOCKET',
path: undefined,
host: 'localhost',
port: undefined,
localAddress: undefined,
command: 'CONN'
}
I thought its an unhandled promise issue so i added a return new promise, but still nothing worked :( .
Please guys i need your help
This is the function
offreEmail : function (brand,model,date,id,email){
return new Promise((resolve,reject)=>{
let readHTMLFile = function (path, callback) {
fs.readFile(path, { encoding: 'utf-8' }, function (err, html) {
if (err) {
callback(err);
throw err;
}
else {
callback(null, html);
}
});
};
let transporter = nodemailer.createTransport({
service: 'ssl0.ovh.net',
port : 587,
secure: false,
auth: {
user: process.env.MAILER_EMAIL,
pass: process.env.MAILER_PASSWORD
},
tls: {
ciphers:'SSLv3',
tls:'TLSv1.2',
}
});
readHTMLFile('./Controllers/email/beefree-ec9f8b73xv.html', function (err, html) {
var template = handlebars.compile(html);
var replacements = {
brand: brand,
model: model,
date : date,
id : id
};
var htmlToSend = template(replacements);
var mailOptions = {
from: process.env.MAILER_EMAIL,
to: email,
subject: 'Votre offre a été reçue avec succès',
html: htmlToSend
};
transporter.sendMail(mailOptions, async (error, response) =>{
if (error){
console.log(error);
resolve(false)
} else {
console.log('Email sent: ' + info.response);
resolve(true)
}
});
});
})
},
and im calling it from an API as shown below
offre
.save()
.then(result => {
mailer.offreEmail(result.brand.toUpperCase(), result.model.toUpperCase(), result.date, result._id, result.email)
res.status(200).json(result)
photo_name = [];
})
.catch(error => {
res.status(400).json(error.message)
photo_name = [];
})
So i found out that this is not a promise issue,
I added secureConnection: true,
And i got rid of both return new Promise and the tls options since they both had no effect and i also changed service to host
Then I started using smtpTransport as shown the code bellow
var smtpTransport = require('nodemailer-smtp-transport');
offreEmail : function (brand,model,date,id,email){
var readHTMLFile = function (path, callback) {
fs.readFile(path, { encoding: 'utf-8' }, function (err, html) {
if (err) {
callback(err);
throw err;
}
else {
callback(null, html);
}
});
};
var transporter = nodemailer.createTransport(smtpTransport({
host: 'ssl0.ovh.net', //mail.example.com (your server smtp)
port: 587, //2525 (specific port)
secureConnection: true, //true or false
auth: {
user: process.env.MAILER_EMAIL,
pass: process.env.MAILER_PASSWORD
}
}));
readHTMLFile('./Controllers/email/beefree-ec9f8b73xv.html', function (err, html) {
var template = handlebars.compile(html);
var replacements = {
brand: brand,
model: model,
date : date,
id : id
};
var htmlToSend = template(replacements);
var mailOptions = {
from: process.env.MAILER_EMAIL,
to: email,
subject: 'Votre offre a été reçue avec succès',
html: htmlToSend
};
transporter.sendMail(mailOptions, function (error, response) {
if (error){
console.log(error);
} else {
console.log('Email sent: ' +response);
}
});
});
},

I am trying to return JSON for successful authentication via passportjs but I'm getting "Error Cannot set headers after they are sent to the client."

I am trying to send a JSON file after registering a user and authenticating them. Callback function after authentication is running as well, but the following error is thrown. Please help!
Here is the controller function :
var passport = require("passport");
var connection = require("../config/dataBase");
var User = connection.models.User;
const signUp = (req, res) => {
User.register(
{
username: req.body.username,
data: {
firstName: req.body.firstName,
lastName: req.body.lastName,
},
},
req.body.password,
function (err, user) {
if (err) {
console.log(err);
} else {
console.log("1");
passport.authenticate("local", {
failureRedirect: "/login",
failureMessage: true,
}),
(function (err, usr) {
console.log("Registered and Authenticated");
return res.json({
authenticated: true,
status: {
message: "Successfully Signed up and authenticated",
code: 200,
},
});
})(req, res);
}
}
);
res.end();
};
module.exports = signUp;
Here is the full Error:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:372:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (/home/pristyncare/Documents/MERN-Blog/Server/node_modules/express/lib/response.js:767:10)
at ServerResponse.json (/home/pristyncare/Documents/MERN-Blog/Server/node_modules/express/lib/response.js:264:10)
at /home/pristyncare/Documents/MERN-Blog/Server/controllers/signupController.js:26:24
at /home/pristyncare/Documents/MERN-Blog/Server/controllers/signupController.js:33:13
at /home/pristyncare/Documents/MERN-Blog/Server/node_modules/passport-local-mongoose/index.js:247:30
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
My bad, i was sending response twice. Just needed to remove res.end() part at the end of snippet and it worked.

trying to setup password recovery in nodejs using nodemailer

tried to setup a password recovery in my nodejs project using nodemailer.I have got 'no recipients defined' error. how to fix the code?.
here is my code:
app.post('/forgotpass', (req, res, next)=> {
let recoveryPassword = '';
async.waterfall([
(done) => {
crypto.randomBytes(20, (err , buf) => {
let token = buf.toString('hex');
done(err, token);
});
},
(token, done) => {
User.findOne({username : req.body.username})
.then(user => {
if(!user) {
console.log("user does not exists");
return res.redirect('/forgotpass');
}
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 1800000; // 1/2 hours
user.save(err => {
done(err, token, user);
});
});
},
(token, user) => {
let smtpTransport = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
auth: {
user: 'test#gmail.com',
pass: 'testpass'
}
});
let mailOptions = {
to: user.email,
from : 'Ghulam Abbas myapkforest#gmail.com',
subject : 'Recovery Email from Auth Project',
text : 'Please click the following link to recover your passoword: \n\n'+
'http://'+ req.headers.host +'/reset/'+token+'\n\n'+
'If you did not request this, please ignore this email.'
};
smtpTransport.sendMail(mailOptions, err=> {
console.log(err);
res.redirect('/forgotpass');
});
}
], err => {
if(err) res.redirect('/forgotpass');
if (err )console.log(err);
});
});
and here is the error I got :
Error: No recipients defined
at SMTPConnection._formatError (C:\Users\JITHENDRA\Desktop\project\node\Secrets-Starting-Code\node_modules\nodemailer\lib\smtp-connection\index.js:784:19)
at SMTPConnection._setEnvelope (C:\Users\JITHENDRA\Desktop\project\node\Secrets-Starting-Code\node_modules\nodemailer\lib\smtp-connection\index.js:995:34)
at SMTPConnection.send (C:\Users\JITHENDRA\Desktop\project\node\Secrets-Starting-Code\node_modules\nodemailer\lib\smtp-connection\index.js:615:14)
at sendMessage (C:\Users\JITHENDRA\Desktop\project\node\Secrets-Starting-Code\node_modules\nodemailer\lib\smtp-transport\index.js:227:28)
at C:\Users\JITHENDRA\Desktop\project\node\Secrets-Starting-Code\node_modules\nodemailer\lib\smtp-transport\index.js:285:25
at SMTPConnection._actionAUTHComplete (C:\Users\JITHENDRA\Desktop\project\node\Secrets-Starting-Code\node_modules\nodemailer\lib\smtp-connection\index.js:1537:9)
at SMTPConnection.<anonymous> (C:\Users\JITHENDRA\Desktop\project\node\Secrets-Starting-Code\node_modules\nodemailer\lib\smtp-connection\index.js:550:26)
at SMTPConnection._processResponse (C:\Users\JITHENDRA\Desktop\project\node\Secrets-Starting-Code\node_modules\nodemailer\lib\smtp-connection\index.js:942:20)
at SMTPConnection._onData (C:\Users\JITHENDRA\Desktop\project\node\Secrets-Starting-Code\node_modules\nodemailer\lib\smtp-connection\index.js:749:14)
at TLSSocket.SMTPConnection._onSocketData (C:\Users\JITHENDRA\Desktop\project\node\Secrets-Starting-Code\node_modules\nodemailer\lib\smtp-connection\index.js:195:44)
at TLSSocket.emit (events.js:310:20)
at addChunk (_stream_readable.js:286:12)
at readableAddChunk (_stream_readable.js:268:9)
at TLSSocket.Readable.push (_stream_readable.js:209:10)
at TLSWrap.onStreamRead (internal/stream_base_commons.js:186:23) {
code: 'EENVELOPE',
command: 'API'
}
that's the error I have got.please fix the code
I just want the node mailer to send the mail after verifying the user exists or not
This error means that you aren't passing a mailOptions.to value, so the user.email value is empty or not a valid email address. If you utilize async/await you can write the code more concisely and avoid using async.waterfall to make it easier to debug. There are a few changes/typos noted below -
// define transport here, outside the handler
const smtpTransport = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
auth: {
user: 'test#gmail.com',
pass: 'testpass'
}
});
// use async function as the handler
app.post('/forgotpass', async (req, res) => {
try {
const user = await User.findOne({username : req.body.username});
if (!user) {
console.log("user does not exists");
return res.redirect('/forgotpass');
}
// make sure you have a valid email here
console.log(`Sending email to ${user.email}`);
// get token here once we have a valid user
const token = crypto.randomBytes(20);
// update the user with the token
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 1800000; // 1/2 hours
await user.save();
// send the email
await smtpTransport.sendMail({
to: user.email,
from : 'Ghulam Abbas <myapkforest#gmail.com>', // <-- wrap email address in <>
subject : 'Recovery Email from Auth Project',
text : 'Please click the following link to recover your passoword: \n\n'+ // <-- typo: "passoword" should be "password"
'http://'+ req.headers.host +'/reset/'+token+'\n\n'+ // <-- use HTTPS!
'If you did not request this, please ignore this email.'
});
} catch (err) {
// catch all exceptions here...
console.log(err);
}
// everything redirects to the GET handler for forgotpass
return res.redirect('/forgotpass');
});

Nodemailer not loggin in

I want to send an email from node backend and I am using the nodemailer library for express to achieve that. I have written the following code to configure the transport and other details for nodemailer
let transport = nodemailer.createTransport({
host: 'mail.myrandomhost.in',
port: 587,
tls: {
rejectUnauthorized:false
},
secure: false,
auth: {
user: 'me#myemail.in',
pass: 'Gr3aseMonk3y'
}
});
const message = {
from: 'me#myemail.in',
to: 'youremail#gmail.com',
subject: 'test email',
html: '<h1>Hey</h1><p>This is test <b>Tesla</b> email</p>'
};
transport.sendMail(message, function(err, info) {
if (err) {
console.log('-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=');
console.log("FAILED");
console.log('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-');
console.log(err)
} else {
console.log('====================================');
console.log("Email sent");
console.log('====================================');
console.log(info);
}
});
When I run this, I get the following error
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
FAILED
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Error: Invalid login: 535 Incorrect authentication data
at SMTPConnection._formatError (/Users/sarthak/Desktop/CodingEnvironments/NodeJS/templates/node_modules/nodemailer/lib/smtp-connection/index.js:784:19)
at SMTPConnection._actionAUTHComplete (/Users/sarthak/Desktop/CodingEnvironments/NodeJS/templates/node_modules/nodemailer/lib/smtp-connection/index.js:1523:34)
at SMTPConnection.<anonymous> (/Users/sarthak/Desktop/CodingEnvironments/NodeJS/templates/node_modules/nodemailer/lib/smtp-connection/index.js:550:26)
at SMTPConnection._processResponse (/Users/sarthak/Desktop/CodingEnvironments/NodeJS/templates/node_modules/nodemailer/lib/smtp-connection/index.js:942:20)
at SMTPConnection._onData (/Users/sarthak/Desktop/CodingEnvironments/NodeJS/templates/node_modules/nodemailer/lib/smtp-connection/index.js:749:14)
at TLSSocket.SMTPConnection._onSocketData (/Users/sarthak/Desktop/CodingEnvironments/NodeJS/templates/node_modules/nodemailer/lib/smtp-connection/index.js:195:44)
at TLSSocket.emit (events.js:210:5)
at addChunk (_stream_readable.js:309:12)
at readableAddChunk (_stream_readable.js:290:11)
at TLSSocket.Readable.push (_stream_readable.js:224:10)
at TLSWrap.onStreamRead (internal/stream_base_commons.js:182:23) {
code: 'EAUTH',
response: '535 Incorrect authentication data',
responseCode: 535,
command: 'AUTH PLAIN'
}
I am using the correct details. How do I solve this?
You entered the wrong data. you must change host, from to real addresses.
Example:
let transport = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
tls: {
rejectUnauthorized:true
},
secure: false,
auth: {
user: 'yourRealEmail#gmail.com',
pass: 'yourPassword'
}
});
const message = {
from: 'yourRealEmail#gmail.com',
to: 'RealEmailAddress#gmail.com',
subject: 'test email',
html: '<h1>Hey</h1><p>This is test <b>Tesla</b> email</p>'
};
transport.sendMail(message, function(err, info) {
if (err) {
console.log('-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=');
console.log("FAILED");
console.log('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-');
console.log(err)
} else {
console.log('====================================');
console.log("Email sent");
console.log('====================================');
console.log(info);
}
});

Nodemailer is giving error

I'm using Nodemailer for sending a forget password mail with Gmail service.I tried to reach to the same error earlier in the StackOverflow, but I couldn't find the solution. Please help me, I have no idea why it is giving error like,
"TypeError: Cannot create property 'mailer' on string 'smtpTransport'"
Here is my code below-
var nodemailer = require('nodemailer');
app.post('/forgot', function(req, res, next) {
async.waterfall([
function(done) {
crypto.randomBytes(20, function(err, buf) {
var token = buf.toString('hex');
done(err, token);
});
},
function(token, done) {
User.findOne({ email: req.body.email }, function(err, user) {
if (!user) {
req.flash('error', 'No account with that email address exists.');
return res.redirect('/forgot');
}
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
user.save(function(err) {
done(err, token, user);
});
});
},
function(token, user, done) {
console.log(token, "Token");
console.log(user, "user")
var smtpTransport = nodemailer.createTransport('SMTP', {
service: 'gmail',
auth: {
user: 'abc#gmail.com',
pass: '123456'
}
});
var mailOptions = {
to: user.email,
from: 'myproducts#mailinator.com',
subject: 'My Products Password Reset',
text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
'http://' + req.headers.host + '/reset/' + token + '\n\n' +
'If you did not request this, please ignore this email and your password will remain unchanged.\n'
};
smtpTransport.sendMail(mailOptions, function(err) {
req.flash('info', 'An e-mail has been sent to ' + user.email + ' with further instructions.');
done(err, 'done');
});
}
], function(err) {
if (err) return next(err);
res.redirect('/forgot');
});
});
And the error is something like this-
/home/cis/Desktop/myproducts/node_modules/mongodb/lib/utils.js:132
throw err;
^
TypeError: Cannot create property 'mailer' on string 'smtpTransport'
at Mail (/home/cis/Desktop/myproducts/node_modules/nodemailer/lib/mailer/index.js:45:33)
at Object.module.exports.createTransport (/home/cis/Desktop/myproducts/node_modules/nodemailer/lib/nodemailer.js:52:14)
at /home/cis/Desktop/myproducts/app.js:185:38
at nextTask (/home/cis/Desktop/myproducts/node_modules/async/dist/async.js:5310:14)
at next (/home/cis/Desktop/myproducts/node_modules/async/dist/async.js:5317:9)
at /home/cis/Desktop/myproducts/node_modules/async/dist/async.js:958:16
at /home/cis/Desktop/myproducts/app.js:177:11
at /home/cis/Desktop/myproducts/node_modules/mongoose/lib/model.js:3913:16
at model.$__save.error (/home/cis/Desktop/myproducts/node_modules/mongoose/lib/model.js:342:7)
at /home/cis/Desktop/myproducts/node_modules/kareem/index.js:297:21
at next (/home/cis/Desktop/myproducts/node_modules/kareem/index.js:209:27)
at Kareem.execPost (/home/cis/Desktop/myproducts/node_modules/kareem/index.js:217:3)
at _cb (/home/cis/Desktop/myproducts/node_modules/kareem/index.js:289:15)
at $__handleSave (/home/cis/Desktop/myproducts/node_modules/mongoose/lib/model.js:280:5)
at /home/cis/Desktop/myproducts/node_modules/mongoose/lib/model.js:208:9
at args.push (/home/cis/Desktop/myproducts/node_modules/mongodb/lib/utils.js:404:72)
[nodemon] app crashed - waiting for file changes before starting...
The Nodemailer structure has been changed, try use this :
smtpTransport = nodemailer.createTransport({
service: 'Gmail',
auth: {
xoauth2: xoauth2.createXOAuth2Generator({
user: 'youremail#gmail.com',
//and other stuff here
});
}
});
var nodemailer = require("nodemailer");
var smtpTransport = nodemailer.createTransport({
service: "Yahoo", // sets automatically host, port and connection security settings
auth: {
user: "xxxxxxxxxx95#yahoo.com",
pass: "xxxxxxxxxxxx"
}
});
function mail(messageBody) {
let messageBodyJson = JSON.stringify(messageBody)
smtpTransport.sendMail({ //email options
from: "xxxxxxxxxx95#yahoo.com", // sender address. Must be the same as authenticated user if using Gmail.
to: "xxxxxxxxxx95#gmail.com", // receiver
subject: "Emailing with nodemailer", // subject
text: messageBodyJson // body
}, function(error, response){ //callback
if(error){
console.log("error",error);
}else{
console.log(response);
}
// smtpTransport.close(); // shut down the connection pool, no more messages. Comment this line out to continue sending emails.
});
}
mail("your mail message");
Try this.
Link to a similar question
Gmail / Google app email service requires OAuth2 for authentication. PLAIN text password will require disabling security features manually on the google account.
To use OAuth2 in Nodemailer, refer: https://nodemailer.com/smtp/oauth2/
Sample code:
var email_smtp = nodemailer.createTransport({
host: "smtp.gmail.com",
auth: {
type: "OAuth2",
user: "youremail#gmail.com",
clientId: "CLIENT_ID_HERE",
clientSecret: "CLIENT_SECRET_HERE",
refreshToken: "REFRESH_TOKEN_HERE"
}
});

Categories