nodemailer email not sent and no errors logged - javascript

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

Related

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?

not delivering emails sent with nodemailer

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));
}
});

How to use nodemailer with claudia-api-builder

I am trying to create a simple REST API I can post an email to, to then email myself. I am using nodemailer and had set it up as an express app and it all worked fine confirming my authentication etc. is fine. I wanted to host it online so I have used claudia.js to create a lambda and API gateway setup but this seems to have broken it.
The Code
const nodemailer = require('nodemailer');
const secrets = require('./secret');
const apiBuilder = require('claudia-api-builder');
api = new apiBuilder();
module.exports = api;
var mailOptions;
var logMsg = "none";
api.post('/email', async (req, res) => {
mailOptions = {
from: secrets.email,
to: secrets.email,
subject: 'Email From: ' + req.body.senderEmail + ' | ' + req.body.subject,
text: req.body.content,
};
sendMail(mailOptions);
return logMsg;
})
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: secrets.email,
pass: secrets.pwd
}
});
function sendMail(mailOptions) {
logMsg="Starting Send Function";
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
logMsg = error;
return error;
} else {
logMsg = "Send Complete";
return true;
}
});
logMsg="Function finished";
}
When I debug via postman, by posting a raw JSON
{
"senderEmail": "test2",
"subject": "test",
"content":"test"
}
I receive "Function Finished" Which I dont really see how it is possible as surely the if or else should've fired under transporter.sendMail(..., returning from the function. I also don't receive an email which is my end goal
I had the same problem until I started returning the transporter
return transporter.sendMail(mailOptions)
.then(info => {
console.log('email sent: ', info)
return {'status': 'OK'}
})
.catch(err => {
console.log('email error: ', err)
return {'status': 'ERROR'}
})

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();
}

When creating a login, an empty object arrives

The empty object comes to login. The use of registration, done in the similarity of the login and so everything works. By sending a request through Postman, you can register a user and check whether such one exists in the database. When you send a request for a login, instead of a token, a message comes from the last block 'else' “User with such email address not found”.
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const keys = require('../config/keys');
module.exports.login = async function (req, res) {
console.log('req.body', req.body); //Empty object {}
const candidate = await User.findOne({
email: req.body.email
});
if (candidate) {
const passwordResult = bcrypt.compareSync(req.body.password,
candidate.password);
if (passwordResult) {
const token = jwt.sign({
email: candidate.email,
userId: candidate._id
}, keys.jwt, {expiresIn: 60 * 60});
res.status(200).json({
token: `Bearer ${token}`
})
} else {
res.status(401).json({
message: 'Passwords do not match'
})
}
} else {
console.log(req.body.email);
console.log(candidate);
res.status(404).json({
message: 'User with such email address not found'
})
}
};
module.exports.register = async function (req, res) {
console.log('req.body', req.body);
const candidate = await User.findOne({
email: req.body.email
});
if (candidate) {
res.status(409).json({
message: "User with this email address already exists"
})
} else {
const salt = bcrypt.genSaltSync(10);
const password = req.body.password;
const user = new User({
email: req.body.email,
password: bcrypt.hashSync(password, salt)
});
try {
await user.save();
res.status(201).json(user)
} catch (e) {
}
}
};
! [Registration works correctly] (https://imgur.com/a/9T5vRMD)
! [Login does not work correctly] (https://imgur.com/a/rQOiw2w) "Must be token, because this user is already there"
I found the answer myself. I use " x-form-urlencoded", the login works correctly and I get a valid token. Apparently the problem is in the internal implementation of the Postman, because the data entered with the help of "rav" should also be valid.

Categories

Resources