Using nodemailer to send emails not working - javascript

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?

Related

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

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

How to add an event listener to trigger a server side email function?

So, I have an express application serving a static index.html page, and a function in my app.js file that sends an email when the server starts up.
What I'd like to do is send the email only when a user hits a 'submit' button on a form (and the form is successfully sent, so on success-confirmation, preferably).
How do I get my program to "listen" for an onClick / form-successfully-sent event and then run the server side code I have that sends an email?
const http = require('http');
const nodemailer = require('nodemailer');
const express = require('express');
const app = express();
const port = 8080;
app.listen(port, () => console.log(`App listening on port ${port}!`));
app.use(express.static('public'));
app.get('/', (req, res) => res.send('index.html'))
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'USERNAME#GMAIL.COM',
pass: 'PASSWORD'
}
});
const mailOptions = {
from: 'USERNAME#GMAIL.COM',
to: 'USERNAME2#GMAIL.COM',
subject: 'Sending Email using Node.js',
text: 'That was easy!'
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
})
I would like to trigger the transporter.sendMail method/function when a user successfully submits a form.
Thanks!
Add a route on your server that will handle form submissions. There are multiple ways to do this, however, as a simple example, look at the code below:
app.post("/send", function(req, res, next) {
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: "test-email#gmail.com",
pass: "test123"
}
});
const mailOptions = {
from: `${req.body.email}`,
to: "test-email#gmail.com",
subject: `${req.body.name}`,
text: `${req.body.message}`,
replyTo: `${req.body.email}`
};
transporter.sendMail(mailOptions, function(err, res) {
if (err) {
console.error("there was an error: ", err);
} else {
console.log("here is the res: ", res);
}
});
});
Then, in your client application, call the function below (or something similar) to send the client-side data to the newly-created endpoint:
function sendEmail(name, email, message) {
const options = {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
name: name,
email: email,
message: message
})
};
return fetch("/send", options)
.then(res => res.json())
.then(res => {
console.log("here is the response: ", res);
})
.catch(err => {
console.error("here is the error: ", err);
});
}
You'll have to set up an API endpoint
app.post('/send-mail', function (req, res) {
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
})
})
And then call that from your form code.
onSubmit() {
fetch('/send-mail', {
method: 'POST'
})
}
Edit: typo.
Put this part inside a function and call it when you handle your form request, create parameters in function as needed for f.ex. mailOptions information
function sendEmail(){
const mailOptions = {
from: 'USERNAME#GMAIL.COM',
to: 'USERNAME2#GMAIL.COM',
subject: 'Sending Email using Node.js',
text: 'That was easy!'
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
})
}
const bodyparser = require("body-parser");
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: `${req.body.username}`,
pass: `${req.body.password}`
}
});
const mailOptions = {
from: `${req.body.email}`,
to: 'USERNAME2#GMAIL.COM',
subject: ``${req.body.subject},
text: `${req.body.message}`
};
app.post("/login", (req, res)=>{
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
})
})
remember to do npm install --save body-parser and also app.use(bodyparser.json())

Calling NodeJS function from JS function

I am doing a project based on firebase and I need to link a server-side function that sends an email to the client-side script.
This is my server-side index.js file
const functions = require('firebase-functions');
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'xxx#gmail.com',
pass: 'password'
}
});
var mailOptions = {
from: 'xxx#gmail.com',
to: 'xxx#gmail.com',
subject: 'Sending Email using Node.js',
text: 'That was easy!'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
I am wondering how I could have a button in html call a function in the script that will call the transporter.sendMail. I have never touched node js before so please excuse my lack of knowledge.
If this helps firebase setup my folders to be separated by functions and public for the server-side and client-side files
First initialize your HTML page with jQuery and on submitting the form send an Ajax request to the server as follows
$(document).ready(function() {
$("#formoid").submit(function(event) {
event.preventDefault();
$.ajax({
url: 'http://xxxxxxx.com/contact', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#formoid").serialize(), // post data || get data
success : function(result) {
$('#formoid')[0].reset();
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
Create a route called contact in your NodeJS server and listen for the contact request with All parameters required for your need. In the following case am using an express server and body parser to parse the data from incoming request
app.post('/contact', (req, res) => {
var transporter = nodemailer.createTransport({
service: "Gmail",
auth: {
user: "xxxxx",
pass: "xxxxx"
}
});
var mailOptions = {
from: req.body.email,
to: 'xxxxx#xx.com',
subject: 'Contact form',
text: 'From: ' + req.body.name + '\n Email: ' + req.body.email + '\nMessage: ' + req.body.msg
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
res.status(500).json({
message: "Error",
error: error
})
} else {
res.status(200).json({
message: "Its working",
response: info.response
})
}
});
});
In the above request am sending the name:as name, email: as email and message: as msg

Categories

Resources