not delivering emails sent with nodemailer - javascript

i trying to send emails with in NextJs using nodemailer and it works and the response is success and i watch mailtrap it look like the emails was sent, but the problem is in there that i didn't receive any email and i don't know why its happening and how can i fix this..
its My configure code
import nodemailer from "nodemailer";
async function sendEmail(token, email) {
try {
var transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
});
transporter.verify(function (error, success) {
if (error) {
console.log(error);
} else {
// this console.log will print and every thing is OK!
console.log("Server is ready to take our messages");
}
});
const message = {
to: email,
from: `${process.env.STMP_FROM_NAME} <${process.env.STMP_FROM_EMAIL}>`,
subject: "Reset Password",
html: `
<p>
You Tried to reset your password, then just click this
link to do
this..
</p>
`,
};
await transporter.sendMail(message);
} catch (err) {
console.log(err);
}
}
export default sendEmail;
and its my controller codes
const sendResetMessage = asyncHandler(async (req, res, next) => {
try {
const user = await Users.findOne({ email: req.body.email });
if (!user) {
return next(new ErrorHandler("User not found with this email", 404));
}
// Get reset token
const resetToken = user.generateTokenToResetPassword();
await user.save({ validateBeforeSave: false });
await sendEmail(resetToken, user.email);
res.status(200).json({
success: true,
message: `Email sent to: ${user.email}`,
});
} catch (error) {
console.log(error);
user.resetPasswordToken = undefined;
user.resetPasswordExpire = undefined;
await user.save({ validateBeforeSave: false });
return next(new ErrorHandler(error.message, 500));
}
});

Related

App crashed after the wrong login credential attempt in node .js

Here is my code of login its work when the user enter the right credential but the app crashed when its enter the wrong credential by showing showing the error message "Internal server error" which is right beacause I wriiten in it catch code but what I want the app should not be crashed when the user enter the wrong credentials.
router.post(
"/login",
[
body("email", "you enter wrong email").isEmail(),
body("password", "password cannot be blank").exists(),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { email, password } = req.body;
try {
let user = await User.findOne({ email });
if (!user) {
res.status(400).json({ error: "Please try to login with correct credentials" });
}
const passwordcompare = await bcrypt.compare(password, user.password);
if (!passwordcompare) {
res.status(400).json({ error: "Please Try to login with correct credential" });
}
const data = {
user: {
id: user.id,
},
};
const authtoken = jwt.sign(data, JWTSECRET);
res.json({ authtoken });
} catch (error) {
console.log(error.message);
res.status(500).send("Internal server error");
}
},
);
module.exports = router;
You're not returning after those res.status(400).json()s, so your program just continues on its merry way.
if (!user) {
res.status(400).json({error: "Please try to login with correct credentials"});
return; // add this
}
I think The problem in this line
const passwordcompare = await bcrypt.compare(password, user.password);
When password is undefined or wrong bcrypt.compare will throw an error and the catch block will catch it and return internal server error message
Try add return to res
if (!passwordcompare) {
return res.status(400).json({ error: "Please Try to login with correct credential" });
}
const data = {
user: {
id: user.id,
},
};
const authtoken = jwt.sign(data, JWTSECRET);
return res.json({ authtoken
});
You should add return statements on your error checks, otherwise, the function will keep executing and try to access user.password also if the user has not been found:
router.post(
"/login",
[
body("email", "you enter wrong email").isEmail(),
body("password", "password cannot be blank").exists(),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { email, password } = req.body;
try {
let user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ error: "Please try to login with correct credentials" });
}
const passwordcompare = await bcrypt.compare(password, user.password);
if (!passwordcompare) {
return res.status(400).json({ error: "Please Try to login with correct credential" });
}
const data = {
user: {
id: user.id,
},
};
const authtoken = jwt.sign(data, JWTSECRET);
res.json({ authtoken });
} catch (error) {
console.log(error.message);
res.status(500).send("Internal server error");
}
},
);
module.exports = router;
You do not return res.status() that's why your code crashed.

Using nodemailer to send emails not working

I am creating a project with authentication and after registration this function is supposed to call
exports.sendEmail = async (req, res, next) => {
try {
const mailText = `<body style="text-align: center"><h1>Name Of Company</h1><p>This email was automatically sent to you to confirm your account at<b>Name of Company</b><br />Please press on this link to confirm your account</p></body>`;
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: "example#gmail.com",
pass: "password",
},
});
const options = {
from: "example#gmail.com",
to: "user#gmail.com",
subject: "Confirm Your Email",
html: mailText,
};
transporter.sendMail(options, function (err, info) {
if (err) {
console.log(err);
return res.status(500).json({
err: err,
});
}
return res.status(200).json({
success: true,
data: "Sent: " + info.response,
});
});
} catch (error) {
console.log("Error");
}
}
But the email is not sending and neither the try or catch are sending anything back.
I have also turned on the less secure apps in gmail
How do I fix this?

nodemailer email not sent and no errors logged

I'm trying to use nodemailer to send email but it's not sending any email and the strange thing is that it's also not logging any error.
Here's the code of my route:
router.post("/form", async (req, res) => {
try {
let { name, email, password } = req.body;
let user = await User.create({
name,
email,
password,
});
if (!user) return res.status(501).send("Something went wrong");
let token = await user.getSignedToken();
try {
user.emailToken = await user.verifyEmail();
} catch (ex) {
console.log(ex);
}
try {
await user.save({ validateBeforeSave: false });
} catch (ex) {
console.log(ex);
}
const options = {
expires: new Date(
Date.now() + process.env.JWT_COOKIE_EXPIRE * 24 * 60 * 60 * 1000
),
};
var smtpTransport = nodemailer.createTransport({
service: "Gmail",
auth: {
user: "myEmail",
pass: "myPass",
},
});
var mailOptions = {
from: "myEmail",
to: req.body.email,
subject: "Verify Email Token",
text: `go to the below link\nhttp://localhost:3000/verifyEmail/${emailToken}`,
};
smtpTransport.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log("Email sent: " + info.response);
}
});
res.cookie("token", token, options);
res.send("Check email for activation");
} catch (ex) {
res.send(ex);
}
});
So, it's not sending any email and after it, the res.cookie and the res.send line is also not working. But, the server is not logging any error/exceptions. So, what could be the issue? I used nodemailer in another route (with the same gmail account as this one) and it was working. So, what could be the problem that the code here isn't working?
In the mailoptions object, you are using emailToken and that variable is never defined. Instead, you might wanna use user.emailToken

Why am I getting this 404 error with axios.post()? Using Express/Node?

I'm trying to make a contact form with Nodemailer (first time), and I'm running into a 404 error.
I hope this isn't an obnoxious amount of code to share, I'll try to trim it down as much as I can.
Server.js
const transporter = nodemailer.createTransport({
host: "smtp.ethereal.email",
port: 587,
secure: false,
auth: {
user: creds.USER, // Generated by ethereal
pass: creds.PASS // Generated by ethereal
}
});
transporter.verify((err, success) => {
if(err) {
console.log(err)
} else {
console.log("Server is ready to take messages")
}
})
router.post("/send", (req, res, next) => {
let name = req.body.name
let email = req.body.email
let message = req.body.message
let content = `name: ${name} \n email: ${email} \n message: ${message}`
let mail = {
from: name,
to: "jlbroughton88#gmail.com",
subject: "Test from contact form",
text: content
}
transporter.sendMail(mail, (err, data) => {
if (err) {
res.json({
msg: "Message failed"
})
} else {
res.json({
msg: "Message succeeded!"
})
}
})
})
ContactForm.js (React Component)
I've trimmed the JSX part, the submit trigger works fine. It breaks once it reaches the axios.post() method.
handleSubmit(e) {
e.preventDefault();
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const message = document.getElementById('message').value;
axios.post("http://localhost:3002/send", {
name,
email,
message
})
.then((response) => {
// console.log(response)
if (response.data.msg === 'success') {
alert("Message Sent.");
this.resetForm()
} else if (response.data.msg === 'fail') {
alert("Message failed to send.")
}
})
}
resetForm() {
document.getElementById('contact-form').reset();
}

Does not work post-query when login

I'm trying to verify the user's password using bcrypt. But, unfortunately, my post-request does not work, it just loads for a long time and that's it.
I have a model user.js with this code:
UserSchema.methods.comparePasswords = function (password) {
return bcrypt.compare(password, this.password);
};
And i have a controller auth.js with this code:
export const signin = async (req, res, next) => {
const { login, password } = req.body;
const user = await User.findOne({ login });
if (!user) {
return next({
status: 400,
message: 'User not found'
});
}
try {
const result = await user.comparePasswords(password);
} catch (e) {
return next({
status: 400,
message: 'Bad Credentials'
});
}
req.session.userId = user._id;
req.json(user);
};
The handling of incorrect input works well and the server returns false messages for me, but does not process the correct input.

Categories

Resources