且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 nodemailer 一次发送多封电子邮件

更新时间:2022-11-16 22:55:44

我已经使用 promise.all 测试了 nodeMailer API,但没有发现任何问题 这是我在下面使用的代码,另一件事是您的错误我认为与均衡器或 SQL 相关,导致您得到的错误是由 SQLITE_ERROR 引发的 UnhandledPromiseRejectionWarning:错误:消息失败:450 SQLITE_ERROR:无法在事务中启动事务,还有另外一件事,你在 promise 中编写异步的方式,我认为是错误的,我将在这里与你分享你应该编写函数的方式,但是关于你在运行 promise 之前触发的第一个问题.当您创建一个类似这样的数组 [promise(arg)] 时,您正在调用该函数,因此即使您没有将其放入 promise 中,promise 也会启动并且 node 将处理它.all

I have tested nodeMailer API with promise.all and I did not found any problem with it this is the code I used below, and another thing the error you are getting is I think related to equalizer or SQL cause the error you are getting is being thrown by SQLITE_ERROR UnhandledPromiseRejectionWarning: Error: Message failed: 450 SQLITE_ERROR: cannot start a transaction within a transaction, and another thing the way you are writing async inside the promise all I think is wrong I will share with you here the way you should write the function, but about your fist question about the promises firing before you run promise.all that's all when you create an Array-like this [promise(arg)] you are calling the function at that moment so the promise will start and node will handle it even if you don't put it inside of promise.all

 static async resendUndeliveredMails() {
try {
  const mails = await findAll();
  const mailerPromises = mails.map((mail) => transporter.sendMail(mail.dataValues));
  const responses = await Promise.all(mailerPromises);
  console.log(responses, "All Mails Have Been Sent Successfully");
} catch (e) {
  console.log(e);
}

}

const nodemailer = require("nodemailer");

const transporter = nodemailer.createTransport({
  service: "gmail",
  auth: {
    user: "user",
    pass: "pass", // naturally, replace both with your real credentials or an application-specific password
  },
});

const mailOptions = {
  from: "user@gmail.com",
  to: "test@gmail.com",
  subject: "testing due",
  text: "Dudes, we really need your money.",
};

const mailOptions2 = {
  from: "user@gmail.com",
  to: "test1@gmail.com",
  subject: "LOL due",
  text: "Dudes, we really need your money.",
};

Promise.all([
  transporter.sendMail(mailOptions),
  transporter.sendMail(mailOptions2),
])
  .then((res) => console.log(res))
  .catch((err) => console.log(err));