我已经实现了nodemailer来发送电子邮件。对于电子邮件详细信息,例如电子邮件ID,主题和文本,我在数据库中有一个表格。在该表中,我有一个标记(新的,已处理的)来获取新记录的列表,以便我可以发送新记录的邮件 我在记录列表上使用for循环发送电子邮件。我想知道的是,一旦邮件成功转发,我想更新数据库中的记录标志。我正在node.js中使用sequlize。
var WEBDialerList=[];
var WEBDialerListCount;
SqlObj.WEBDialer.findAll(
{
where: {
IsDeleted: 0,
Status: 'New'
}
}
)
.then(data => {
WEBDialerList = JSON.parse(JSON.stringify(data));
console.log("d.length")
console.log(WEBDialerList.length)
console.log("d.length")
if (WEBDialerList.length > 0) {
for (var i in WEBDialerList){//= 0; i < WEBDialerList.length; i++) {
WEBDialerListCount = i;
"use strict";
const nodemailer = require("nodemailer");
let transporter = nodemailer.createTransport({
service: "Gmail",
auth: {
user: 'abc@gmail.com',
pass: '******'
}
});
var e = WEBDialerList[i].Email;
let mailOptions = {
from: '"ib ik" <ib.ik2093@gmail.com>',
to: e,
subject: "Test Email from Node.js",
text: " scheduler Hello, this is a test email. I have configured my gmail account in node.js to send emails. I am checking, is it configured correctly.",// plain text body
html: "<b> " + WEBDialerList[i].WEBDialerId + " scheduler Hello, this is a test email. I have configured my gmail account in node.js to send emails. I am checking, is it configured correctly.</b>" // html body
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
return console.log(error);
}
else {
console.log("Message sent1: ", info);
console.log(WEBDialerListCount)
transporter.close();
}
})
}
}
})
.catch(function (err) {
console.log(err)
});
在transporter.sendMail中,我只是在循环结束时获取它,因此我很难获取需要更新的记录。
答案 0 :(得分:0)
可能的解决方案可以是:
[..]
// Move this declarations out is a good idea
const nodemailer = require("nodemailer");
let transporter = nodemailer.createTransport({
service: "Gmail",
auth: {
user: 'foobar@gmail.com',
pass: 'foobar'
}
});
[..]
for (var i in WEBDialerList) {
[..]
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
sql.setFlag('errored') // pseudocode
} else {
sql.setFlag('processed') // pseudocode
transporter.close();
}
})
}
[..]
PS:删除您的Gmail凭据!
答案 1 :(得分:0)
请异步等待,而不是保证代码看起来不错且易于阅读。
这是您问题的解决方案。
Promis.all(
WEBDialerList.map(WEBDialer => {
let mailOptions = {
from: '"ib ik" <ib.ik2093@gmail.com>',
to: WEBDialer.email,
subject: "Test Email from Node.js",
text: " scheduler Hello, this is a test email. I have configured my gmail account in node.js to send emails. I am checking, is it configured correctly.",// plain text body
html: "<b> " + WEBDialer.WEBDialerId + " scheduler Hello, this is a test email. I have configured my gmail account in node.js to send emails. I am checking, is it configured correctly.</b>" // html body
};
return new Promise((resolve, reject) => {
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
reject(error)
} else {
console.log("Message sent1: ", info);
console.log(WEBDialerListCount)
// Update user here
transporter.close();
resolve()
}
})
})
})
)
请根据您的要求进行必要的更改。
如果需要更多帮助或有任何疑问,请告诉我。
我希望你喜欢它:)