我正在写一个从联系人表单发送电子邮件的脚本。
电子邮件正在从服务器发送,一切正常,但我无法从服务器返回成功结果,因此无法显示电子邮件已发送的成功消息。我尝试在电子邮件成功发送时在表单下方显示成功消息
<form id="myForm">
<div class="row">
<div class="col-sm-6">
<input id="name" type="text" name="name" placeholder="Name">
</div>
<div class="col-sm-6">
<input id="email" type="email" name="email" placeholder="Email">
</div>
</div>
<input id="subject" type="text" name="subject" placeholder="Subject">
<textarea id="message" name="message" placeholder="Message"></textarea>
<!-- <input type="submit" id="submit" value="Send Message" class="btn"> -->
<button onclick= sendEmail() type="submit" class="btn" id="submit">Send Message</button>
<div id="resultmessage">
<div class="error"></div>
<div class="success"></div>
</div>
</form>
<script type="text/javascript">
function sendEmail() {
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var message = $("#message");
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(message)) {
$.ajax({
url: 'https://.../send-email'
type: 'POST',
headers: {
'Accept': 'application/json',
},
data: {
name: name.val(),
email: email.val(),
subject: subject.val(),
message: message.val()
},
success: function (response) {
console.log("email sent");
if(response.success){
$('.success').text(response.message);
$('#myForm')[0].reset();
}
}
server.use(express.urlencoded({ extended: true }));
router.post("/", (req, res) => {
let transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true,
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD,
},
});
let name = escape(req.body.name);
let email = escape(req.body.email);
let subject = escape(req.body.subject);
let message = escape(req.body.message);
let mailOptions = {
to: "testemail@gmail.com",
subject: req.body.subject,
html: `Name: ${name} <br> Email: ${email} <br> Subject: ${subject} <br> Message: ${message}`
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
return res.status(500).send("Error sending email");
}
res.status(200).send({message: "Email sent!!!!!", success: true});
console.log(`Message sent: ${info.response}`);
});
});```
1条答案
按热度按时间4ngedf3f1#
试试看
router.post("/", async(req, res) => {
以及
您正在
sendMail
中执行异步活动,但是在sendMail
返回时,对浏览器的响应已经处理完毕。