Express使用Nodemailer发送邮件出现重复空白邮件如何解决
问题原因
- 代码中连续调用了两次
transporter.sendMail方法,因此会发出两封邮件 - 第一次调用
await transporter.sendMail({ 完整配置 })时,已经成功发出了第一封内容、收件人正常的邮件,该方法返回的是邮件发送成功的响应结果,并非发信配置对象 - 第二次调用
transporter.sendMail(mail)时,传入的mail是上一步的响应结果,不属于合法发信配置,因此会发出收件人、内容异常的空白邮件
修复方案
删除多余的第二次transporter.sendMail调用即可,如果需要捕获发送结果、打印日志,直接在第一次调用位置处理,两种写法可选:
- 保留await写法,直接打印返回结果:
console.log('called') let transporter = nodemailer.createTransport({ host: 'smtp.gmail.com', port: 465, secure: true, // true for 465, false for other ports auth: { user: process.env.MAIL, pass: process.env.MAIL_PASSWORD, }, }) let message = '' switch (format) { case 'resetPassword': message = `There was recently a request to change the password for your account. If you requested this password change, click the link below to reset your password: <br><br><a href="${passwordKey}">${passwordKey}</a><br><br> If you did not make this request, you can ignore this message and your password will remain the same.` break default: break } // 仅保留一次sendMail调用,直接打印返回的发送结果 let mailSendResult = await transporter.sendMail({ from: `<${process.env.MAIL}>`, to: email, bcc: process.env.MAIL, subject: subject, html: message, }) console.log(mailSendResult)
- 用then链式调用,无需await接收:
// 省略前面transporter创建、message生成的相同代码 transporter.sendMail({ from: `<${process.env.MAIL}>`, to: email, bcc: process.env.MAIL, subject: subject, html: message, }).then((mailSendResult) => { console.log(mailSendResult) })
内容的提问来源于stack exchange,提问作者GlassesUSA
相关产品推荐
相关产品推荐

