我是js和开发的新手,制作节点邮件发送器
Error (node:8244) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to client
错误:没有收件人定义
创建产品的post控制器
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 });
}
};
节点邮件控制器
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 });
}
};
Nodemailer需要一个数组或逗号分隔的列表,您正在使用一个普通字符串作为
to—逗号分隔的收件人电子邮件地址列表或数组,将出现在to:字段
上摘自官方文档https://nodemailer.com/message/
嗨,兄弟,先导入nodemailer
const nodemailer = require("nodemailer");
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'youremail@gmail.com',
pass: 'yourpassword'
}
});
var mailOptions = {
from: 'youremail@gmail.com',
to: 'friend@yahoo.com',
subject: 'Your subject',
text: 'Your message!'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
按照上面提到的步骤,并确保您的发送邮箱没有启用两步验证。