node实现获取表单内元素,图片等生成有邮件内容进行邮件发送代码片段。(form类型:enctype="multipart/form-data")
关注:与req.body.name 不同
var nodemailer = require('nodemailer');
var formidable = require('formidable');
var smtpTransport = require('nodemailer-smtp-transport');
var fs = require('fs');
exports.transMail = function (req, res) {
var id = '53b277d70edc911a14ff6f90';
var name;
var tag = "订单投诉信息";
var result;
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var orderid = fields.orderid;
var questionType = fields.category;
var contacttype = fields.contacttype;
var contact = fields.contact;
var text = fields.content;
var code = fields.code;
var imageName='';
var path='';
if(files.imageName.name !=null && files.imageName.name !='' && files.imageName.name !='undefined' && files.imageName.name!=undefined){
imageName = files.imageName.name;
path = files.imageName.path;
}
var content = '投诉分类:' + questionType + '
' + ' 投诉描述:' + text +
'
' + ' 联系方式:' + contacttype + '
回复方式:' + contact;
var email = config.toMail;
var transport = nodemailer.createTransport(smtpTransport({
host: config.host,
port: config.port,
auth: {
user: config.formMail,
pass: config.pass
},
maxConnections: 5,
maxMessages: 10
}));
//设置邮件内容
var mailOptions;
if (imageName != '' && imageName != null && imageName != 'undefined') {
mailOptions = {
attachments: [
{
filename: imageName,
content: fs.createReadStream(path)
}
],
from: config.formMail, // sender address
to: email, // list of receivers
subject: orderid + tag, // Subject line
text: content, // plaintext body
html: content // html body
}
} else {
mailOptions = {
from: config.formMail, // sender address
to: email, // list of receivers
subject: orderid + tag, // Subject line
text: content, // plaintext body
html: content // html body
}
}
// 发送邮件
transport.sendMail(mailOptions, function (error, info) {
res.set('Content-Type', 'text/plain');
if (error) {
console.log(error);
res.json(error)
} else {
console.log("Message sent: " + info.response);
res.send(200);
}
transport.close();//关闭链接池
}
});
}
});
}