需要将从GET METHOD获取的JSON数据作为电子邮件发送。我需要通过获取的JSON对象定义电子邮件的正文。我不知道该如何解决。
这是我的示例代码:
app.get('/userinfo',(req,res)=>{
dbconn.query('exec sp_GetDueList',(err,rows,fields)=>{
if(!err){
// console.log(rows.recordsets[0][5].Instrument)
for(let i =0; i<= rows.recordsets[0].length-1; i++){
console.log(JSON.stringify(rows.recordsets[0][i].Instrument)+ " "+
JSON.stringify(rows.recordsets[0][i].ID_No)+ " "+JSON.stringify(rows.recordsets[0][i].NextDueDate))
}
email.main(subject, body, res).catch((err) => {
console.log(err);
})
} else{
res.send(err);
}
res.end();
})
})
我得到了这样的输出
Hello here's the json
"Coating Thickness Gauge" "BG-05" "2019-10-17T00:00:00.000Z""Coating Thickness Gauge" "BG-06" "2019-10-17T00:00:00.000Z""Coating Thickness Gauge" "BG-07" "2019-10-17T00:00:00.000Z""Coating Thickness Gauge" "BG-09" "2019-09-15T00:00:00.000Z""Coating Thickness Gauge" "BG-10" "2019-09-15T00:00:00.000Z""Coating Thickness Standards" "TS-04" "2019-09-01T00:00:00.000Z""Deep Freezer" "LE-05" "2019-11-07T00:00:00.000Z""DSC Tester " "LE-04" "2019-09-17T00:00:00.000Z""Freezer " "LE-11" "2019-11-07T00:00:00.000Z""Holiday Detector " "HD-349" "2019-11-20T00:00:00.000Z""Holiday Detector " "HD-488" "2019-10-15T00:00:00.000Z""Jeep Meter " "JM-02" "2019-09-26T00:00:00.000Z""Lab Oven " "LE-09" "2019-11-07T00:00:00.000Z""Lab Oven (CDT) " "LE-06" "2019-11-07T00:00:00.000Z""Microscope" "LE-01" "2019-11-07T00:00:00.000Z""Pit Gauge" "PG-10" "2019-09-25T00:00:00.000Z""Pit Gauge" "PG-11" "2019-09-27T00:00:00.000Z""Pit Gauge" "PG-12" "2019-08-18T00:00:00.000Z""Salt Contamination Meter" "TM-01" "2019-08-24T00:00:00.000Z""UT Gage " "UT-02" "2019-06-25T00:00:00.000Z"
现在我想将此数据作为电子邮件正文发送。我知道这个堆栈溢出的人认为这个问题很愚蠢或太容易了。我到处搜索并且找不到有效的模型。
[如果有人可以帮助,将非常感激
我假设您尚未安装像nodemailer这样的软件包,请通过npm进行安装:npm -i -S nodemailer
var nodemailer = require('nodemailer');
//Here you have to set up your email client, try gmail it's free but otherwise you have to use a service like sendgrid...
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'yourpassword'
}
});
然后您必须在功能内使用电子邮件:
app.get('/userinfo', (req, res) => {
dbconn.query('exec sp_GetDueList', (err, rows, fields) => {
if (!err) {
// console.log(rows.recordsets[0][5].Instrument)
let emailBody;
for (let i = 0; i <= rows.recordsets[0].length - 1; i++) {
console.log(JSON.stringify(rows.recordsets[0][i].Instrument) + " " +
emailBody += JSON.stringify(rows.recordsets[0][i].ID_No) + " " + JSON.stringify(rows.recordsets[0][i].NextDueDate))
}
var mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Sending Email using Node.js',
html: `<h1>Hello here\'s the json</h1><p>${emailBody}</p>`
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
} else {
res.send(err);
}
res.end();
})
})
我尚未测试,也无法真正理解您要尝试执行的操作,但这应该是一个起点,应该将代码拆分为自己的帮助器函数,并使其更可重用。但是,请以此为起点。
签出nodemailer:https://nodemailer.com/about/