我在尝试设置要使用我的节点快递应用提交的联系表单时遇到问题。我已经安装了Nodemailer但我以前没有使用它。这是我到目前为止..................
app.js
var express = require('express');
var fs = require('fs');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var app = express();
app.use(express.static(process.cwd() + '/public'));
app.use(bodyParser.urlencoded({extended: true}));
app.get('/', function(req, res){
res.send(fs.readFileSync('./views/index.html', 'utf8'));
});
app.post('/', function(req, res) {
if(req.body.mail == "" || req.body.subject == "") {
res.send("Error: Email & Subject should not be Blank");
return false;
}
var smtpTransport = nodemailer.createTransport("SMTP", {
host: "smtp.gmail.com",
secureConnection: true,
port: 465,
auth: {
user: '',
pass: ''
}
});
var mailOptions = {
from: "Node Emailer - <email@gmail.com>",
to: req.body.email,
subject: req.body.subject + " -",
html: "<b>"+req.body.description+"<b>"
}
smtpTransport.sendMail(mailOptions, function(error, response) {
if (error) {
res.send("Email could not be sent due to error:" +error);
}else {
res.send("Email has been sent successfully");
}
});
});
app.listen(process.env.PORT || 3000, function() {
console.log("LISTENING!");
});
联络表格
<form action='/' method='post' class='contact-form commentsblock'>
<div>
<label for='g52-name' class='grunion-field-label name'>Name<span>
(required)</span></label>
<input type='text' name='g52-name' id='g52-name' value=''
class='name'
required aria-required='true'/>
</div>
<div>
<label for='g52-email' class='grunion-field-label email'>Email<span>
(required)</span></label>
<input type='email' name='g52-email' id='g52-email' value=''
class='email' required aria-required='true'/>
</div>
<div>
<label for='g52-website' class='grunion-field-label
url'>Website</label>
<input type='text' name='g52-website' id='g52-website' value=''
class='url' />
</div>
<div>
<label for='contact-form-comment-g52-comment' class='grunion-field-label textarea'>Comment<span>(required)</span></label>
<textarea name='g52-comment' id='contact-form-comment-g52-comment' rows='20' class='textarea' required aria-required='true'></textarea>
</div>
<p class='contact-submit'>
<input type='submit' value='Submit' class='pushbutton-wide'/>
</form>
我没有多少使用Node发送邮件的经验。我有一个单页网站,我想要做的就是能够发送电子邮件。如何将表单与Node连接?
答案 0 :(得分:0)
您通过req.body
查看的所有字段都需要与name=""
和<input>
HTML元素的<textarea>
属性相匹配。您似乎无法在脚本中获取任何这些值,有时会随意查看req.body.email
或req.body.mail
。如果您提交console.log(req.body)
,则更愿意看到以下内容:
{
"g52-name": "...",
"g52-email": "...",
"g52-website": "...",
"g52-comment": "..."
}
这是您的表单内容。
app.post('/', function(req, res) {
var subject = req.body["g52-name"];
var mail = req.body["g52-email"];
var website = req.body["g52-website"];
var description = req.body["g52-comment"];
if (!subject || !mail) {
res.send("Error: Email & Subject should not be Blank");
return false;
}
// rest of email-sending code here
// ...
}