i am new to js and development, making node mailer to send email after pushing payloads to db.
Error (node:8244) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
Error: No recipients defined
My post controller for crating product
const mailer = require("../config/nodemailer");
module.exports.create = async (req, res) => {
try {
let product = new Product({
name: req.body.name,
description: req.body.description,
isFeatured: req.body.isFeatured,
});
// await product.save();
await mailer.contact(req, res); // node mailer
// console.log("productCreated ==>>", product);
// res.status(200).json(product);
return res.send("Dummy :product created");
} catch (error) {
console.log("******Error While inserting data******", error);
res.status(500).json({ message: error.message });
}
};
node mailer controller
const nodemailer = require("nodemailer");
exports.contact = async (req, res) => {
// var name = req.body.name;
// var from = req.body.from;
// var message = req.body.message;
// var to = "jn";
try {
let transporter = nodemailer.createTransport({
service: "gmail",
host: "smtp.gmail.com",
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: "**********@gmail.com",
pass: "password",
},
});
//
var mailoptions = {
from: "**********@gmail.com",
to:"**********@gmail.com",
subject: "Sending Email using Node.js",
text: "That was easy!",
};
await transporter.sendMail({
mailoptions,
function(err, res) {
if (err) {
return res.status(200).json({
message: err.message,
});
}
return res.status(200).json({ message: "success" });
},
});
} catch (error) {
console.log(error);
return res.json({ message: message });
}
};
CodePudding user response:
Nodemailer expects an array or a comma separated list, you are using a plain string as to
to - Comma separated list or an array of recipients email addresses that will appear on the To: field
taken from the official documentation https://nodemailer.com/message/
CodePudding user response:
Hi bro first import nodemailer
const nodemailer = require("nodemailer");
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'yourpassword'
}
});
var mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Your subject',
text: 'Your message!'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' info.response);
}
});
follow above mention steps and make sure that your sending mailid has no two step verification enabled.