Unable to send mail in node getting error as UnhandledPromiseRejectionWarning - node.js

Error while send mail:
(node:11928) UnhandledPromiseRejectionWarning: Error: Invalid login: 535 Authentication Failed
I tried nodemailer:
//library.js
const nodemailer = require("nodemailer");
module.exports
= {
transport:function(){
let transporter = nodemailer.createTransport({
host: "smtp.***.email",
port: 587,
secure: false,
auth: {
user: ****,
pass: ****
}
});
return transporter;
}
//controller.js
exports.sendemail = (require,res) => {
let mailOptions =
{
from: '"Fred Foo 👻" <foo#example.com>',
to: "baz#example.com",
subject: "Hello ✔",
text: "Hello world?",
html: "<b>Hello world?</b>"
};
transporter = transport.transporter();
let info = transporter.sendMail(mailOptions)
console.log("Message sent: %s", info.messageId);
}
Message sent:
b658f8ca-6296-ccf4-8306-87d57a0b4321#example.com

use same email at transporter and from on mail-options.
//library.js
const nodemailer = require("nodemailer");
module.exports = {
transport:function(){
let transporter = nodemailer.createTransport(
{
host: "smtp.***.email",
port: 587,
secure: false,
auth: {
user: 'foo#example.com',
pass: ****
}
});
return transporter; }}
//controller.js
exports.sendemail = (require,res) => {
let mailOptions =
{
from: '"Fred Foo 👻" <foo#example.com>',
to: "baz#example.com",
subject: "Hello ✔",
text: "Hello world?",
html: "<b>Hello world?</b>"
};
transporter = transport.transporter();
transporter.sendMail(mailOptions).then((info) =>
{
console.log(info);
return true;
}.catch(err =>
{
console.log("Error:", err);
return false;
});}

Sending a mail is asynchronous process. The warning means that there's rejected promise that wasn't chained. A example from the documentation was pasted the wrong way, await was omitted. sendMail returns a promise that needs to be chained:
transporter.sendMail(mailOptions)
.then(info => {
// success response
})
.catch(err => {
// error response
});

Related

response: '535-5.7.8 Username and Password not accepted. Learn more at\n'

My Node js code is sending proper email on localhost but in backend there showing email and password not valid ?
const nodemailer = require("nodemailer");
const sendEmail = async (subject, message, send_to, sent_from, reply_to) => {
// Create Email Transporter
const transporter = nodemailer.createTransport({
host: process.env.EMAIL_HOST,
port: 465,
secure: true,
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
});
// Options for sending email
const options = {
from: sent_from,
to: send_to,
reply_to: reply_to,
subject: subject,
html: message,
};
// Check email sent successfully or not
transporter.sendMail(options, function (err, info) {
if (err) {
console.log(err);
} else {
console.log(info);
}
});
};
module.exports = sendEmail;

Nodemailer not sending the mail to the address i specify

I'm trying to send a mail to an email address with nodemailer + mailtrap, but i'm receving the mail in the mailtrap account... why is this happening?
here's my code:
const transport = nodemailer.createTransport({
host: "smtp.mailtrap.io",
port: 2525,
auth: {
user: "79a422a4c8485b",
pass: "492900f98e999e",
},
});
app.get("/sendMail", function (req, res) {
const rand = Math.floor(Math.random() * 100 + 54);
const link = `http://localhost:5000/verify?id=${rand}`;
const mailOptions = {
from: "sender#server.com",
to: req.query.to, // DESTINY MAIL, BUT NO MATTER WHAT I PUT IN HERE, I ONLY RECEIVE THE MAIL
// ON THE MAILTRAP ACCOUNT!
subject: "Hello ✔",
text: "Hello world ✔",
html: `Hello,<br> Please Click on the link to verify your email.<br><a href=${link}>Click here to verify</a>`,
};
console.log(mailOptions);
// smtpTransport.sendMail();
transport.sendMail(mailOptions, function (error: any, response: any) {
if (error) {
console.log("no se pudo mandar el mail porque ->", error);
res.end("error");
} else {
console.log("response", response);
console.log(`Message sent: ${response.message}`);
res.send("done");
}
});
});
What am i doing wrong?

not sure why nodemailer isnt working properly

Not sure why this isnt working properly. i think the configuration looks right but I keep getting this error :getaddrinfo ENOTFOUND smpt.mydomian.com
let transporter = nodemailer.createTransport({
host: "smtp.mydomain.com",
port: 465,
secure: true,
auth: {
user: "abc#mydomain.com",
pass: "password",
},
});
let mailOptions = {
from: email,
to: "abc#domail.com",
subject: `New Lead ${fullName}`,
text: newMail,
};
// step 3
transporter.sendMail(mailOptions, (err, data) => {
if (err) {
console.log("there is an error " + err);
} else {
console.log("mail sent successfully");
}
});
});
in my opinion its better to create a class for that just like this
class Mailer {
sendMail = async (emailAddress) => {
let transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: testUser,
pass: testPass,
},
});
const option = {
from: `${EMAIL_ADDRESS}`,
to: emailAddress,
subject: "test Subject",
text: "Test text",
};
await transporter.sendMail(option, (err, info) => {
if (!err) {
console.log(`Email sent Successfully ... !`.green.underline.bold);
return true;
} else {
console.log(
`We have problem while sendil Email ... !`.red.underline.bold
);
return false;
}
});
};
}
i hope this class help you

nodemailer sendEmail doesn't wait in Node.js

When I make a request to my endpoint I need to get a successful response only if the email is sent! otherwise, it should throw an error:
myendpoint.js
router.post("/", upload.none(), async (req, res) => {
try {
let body = JSON.parse(req.body.contact);
await getDb("messages").insertOne({
name: body.name,
email: body.email,
phone: body.phone,
subject: body.subject,
message: body.message,
});
await sendEmail(body);
res.send(
JSON.stringify({
success: true,
msg: "Message has been sent successfully",
})
);
} catch (err) {
res.send(JSON.stringify({ success: false, msg: err }));
}
});
sendEmail.js
const sendEmail = async function (props) {
const transporter = nodemailer.createTransport({
service: process.env.EMAIL_SERVICE,
host: process.env.EMAIL_HOST,
auth: {
user: process.env.EMAIL_FROM,
pass: process.env.EMAIL_PASS,
},
});
const mailOptions = {
from: process.env.EMAIL_FROM,
to: process.env.EMAIL_TO,
name: props.name,
email: props.email,
phone: props.phone,
subject: props.subject,
text: props.message,
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
throw new Error("Message did Not send!");
}
});
};
the problem is before "await sendEmail(body);" ends and i get the error, i get the "Message has been sent successfully" and then server crashes!
what am i missing?
Check document function sendMail from nodemailer at here
If callback argument is not set then the method returns a Promise object. Nodemailer itself does not use Promises internally but it wraps the return into a Promise for convenience.
const sendEmail = async function (props) {
const transporter = nodemailer.createTransport({
service: process.env.EMAIL_SERVICE,
host: process.env.EMAIL_HOST,
auth: {
user: process.env.EMAIL_FROM,
pass: process.env.EMAIL_PASS,
},
});
const mailOptions = {
from: process.env.EMAIL_FROM,
to: process.env.EMAIL_TO,
name: props.name,
email: props.email,
phone: props.phone,
subject: props.subject,
text: props.message,
};
// remove callback and function sendMail will return a Promise
return transporter.sendMail(mailOptions);
};
Hello you can change your Transporter sendMail to :
return await transporter.sendMail(mailOptions);
Or You can Use Promise.
const handler = async ({ subject, name, body, contact }) => {
const transporter = nodemailer.createTransport({
service: "zoho",
// Disable MFA here to prevent authentication failed: https://accounts.zoho.com/home#multiTFA/modes
// ********************* OR *****************
// set up Application-Specific Passwords here: https://accounts.zoho.com/home#security/device_logins
auth: { user: process.env.NEXT_PUBLIC_EMAIL_ADDRESS, pass: process.env.NEXT_PUBLIC_EMAIL_PASSWORD },
});
return transporter
.sendMail(mailOptions({ subject, name, body, contact }))
.then((info) => {
if (process.env.NODE_ENV !== "production") console.log("Email sent: " + info.response);
return true;
})
.catch((err) => {
if (process.env.NODE_ENV !== "production") console.log("error sending mail", err);
return false;
});
};

Send confirmation response after Nodemailer sendMail function done?

I need to return some response when I send a email through Nodemailer and I have this function:
async function dispatchEmail(email) {
const transporter = nodemailer.createTransport({
service: `${nconf.get('EMAIL_SMTP_SERVICE')}`,
auth: {
user: nconf.get('EMAIL_ACCOUNT'),
pass: nconf.get('EMAIL_PASSWORD'),
},
});
const mailOptions = {
from: `"Shagrat Team "${nconf.get('EMAIL_ACCOUNT')}`,
to: email,
subject: 'Hi from Shagrat Team !',
text: '',
html: '',
};
const success = await transporter.sendMail(mailOptions, async (error, sent) => {
if (error) {
return error;
}
return {some_response};
});
return success;
}
Where I need to send{some_response} with some value either true, false or something else, but I got 'undefined' value inside the same function or calling it externally:
const success = await dispatchEmail(emailConsumed);
What value can I return and catch it? because I need to test this function.
An exit is to return the transporter.sendmail () itself, which is a promise, in the return contera the data of the sending or the error, it is good to use a trycatch for other errors.
async function dispatchEmail(email) {
const transporter = nodemailer.createTransport({
service: `${nconf.get('EMAIL_SMTP_SERVICE')}`,
auth: {
user: nconf.get('EMAIL_ACCOUNT'),
pass: nconf.get('EMAIL_PASSWORD'),
},
});
const mailOptions = {
from: `"Shagrat Team "${nconf.get('EMAIL_ACCOUNT')}`,
to: email,
subject: 'Hi from Shagrat Team !',
text: '',
html: '',
};
return transporter.sendMail(mailOptions)
}
Another option is to use the nodemailer-promise module.
const success = await dispatchEmail(emailConsumed);
Result:
console.log(sucess);
{ envelope:
{ from: 'example#example.com',
to: [ 'example2#example.com' ] },
messageId:'01000167a4caf346-4ca62618-468f-4595-a117-8a3560703911' }

Resources