想实现用户点击提交表单之后,将表单的内容以邮件的形式发送到指定的邮箱,
服务器端用 node.js ,发送邮件用 nodemailer 模块。
我的思路是给提交按钮绑定 submitData (),通过 xhr 发送到服务器,
在后台获取并替换 mailOptions 的 content 。
代码如下
单独运行已经可以发送邮件,
var nodemailer = require ('nodemailer');
var transporter = nodemailer.createTransport ({
service: 'hotmail',
auth: {
user: '[email protected]',
pass: '000000'
}
});
var mailOptions = {
from: '[email protected]', // sender address
to: '[email protected]', // list of receivers
subject: 'Hello', // Subject line
text: 'Hello world', // plaintext body
html: '<h1>Hello world </h1>' // content
};
transporter.sendMail (mailOptions, function (error, info ){
if (error ){
console.log (error );
}else{
console.log ('Message sent: ' + info.response );
}
});
function submitData () {
var xhr =creatXHR ();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 ) {
if (xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 ){
alert (xhr.responseText );
} else {
alert ("Request was unsuccessful:" + xhr.status );
}
}
};
xhr.open ("post","postexmple.js",ture );
xhr.setRequestHeader ('Content-Type',"application/x-www-form-urlencoded");
var form = documnet.getElementById ('user-info')
xhr.send (serialize (form ));
}