我有一个表单,我希望输入字段中的数据发送到我的电子邮件。我正在使用nodemailer将其发送到我的电子邮箱。香港专业教育学院尝试使用req.body.name(输入字段的名称),但它说它是未定义的。任何的想法? 理想情况下,我希望电子邮件显示From:XXXX To:XXXX Time:XX:XX Date:XX:XX:XX。
提供表单和node.js代码。
<form action="/send-email" method="post">
<ul class="inputs">
<li>
<label for="from">From</label>
<input type="text" id="from" name="from" />
</li>
<li>
<label for="to">To</label>
<input type="text" id="to" name="to" />
</li>
<li>
<label for="date">Date</label>
<input type="date" id="date" name="date" />
</li>
<li>
<label for="time">Time</label>
<input type="time" id="time" name="time" />
</li>
<li>
<button>Request</button>
</li>
</ul>
</form>
Node.js的
var express = require('express');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');
var nodemailer = require("nodemailer");
var smtpTransport = require('nodemailer-smtp-transport');
app.set('port', 3000);
app.use(express.static(path.join(__dirname, 'public')));
var server = app.listen(app.get('port'), function() {
var port = server.address().port;
console.log('Magic happens on port ' + port);
});
var smtpTransport = nodemailer.createTransport(smtpTransport({
service: 'Gmail',
auth: {
user: 'naomikudren@gmail.com',
pass: '####'
}
}));
app.post('/send-email', function(req, res) {
var mailOptions = {
from: '"Naomi" <naomikudren@gmail.com>', // sender address
to: "naomikudren@gmail.com", // list of receivers
subject: 'Request ', // Subject line
text: req.body.to // plaintext body
};
smtpTransport.sendMail(mailOptions, function(error, info) {
if (error) {
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
res.redirect("/index.html");
});
答案 0 :(得分:2)
您没有使用bodyParser。你需要使用
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())