Nodemailer gmail connection closed with a lot of emails
I have exactly the same problem as this post: Send multi-user emails with nodemailer and gmail
When sending too many emails with nodemailer and gmail, I get a 421 error referring to too many concurrent sessions.
What can I do to avoid opening too many sessions?
I already go to google to confirm that I was not blocked by any restrictions (I did not get to the daily mail number and there is no mail / minute limit). I tried to wait for each mail to be sent before sending a new one; create and close a new transport on every mail, but I keep getting this error after about 100th mail.
Here's the complete error:
{ [Error: Mail command failed: 421 4.7.0 Try again later, closing
connection. (MAIL) e17sm2124566ede.14 - gsmtp]
code: 'EENVELOPE',
response: '421 4.7.0 Try again later, closing connection. (MAIL)
e17sm2124566ede.14 - gsmtp',
responseCode: 421,
command: 'MAIL FROM' }
And my code:
Nodemailer settings:
function setMailTransport () {
return nodemailer.createTransport(smtpTransport({
service: 'gmail',
ignoreTLS: true,
auth: {
xoauth2: xoauth2.createXOAuth2Generator({
user: 'xxxxxx',
clientId: 'xxxxxx',
clientSecret: 'xxxxxx',
refreshToken: 'xxxxxx'
})
}
}))
}
Sending unique mail:
async function sendEmail (mail) {
// mail is an object {from, to, subject, text, html}
const transport = setMailTransport()
try {
await transport.sendMail(mail)
await transport.close()
return 1
} catch (err) {
console.log(err)
await transport.close()
return 0
}
}
Recursive async / await function to wait for mail to be sent before sending a new message:
async function sendAlerts (mails, index, numberOfMailSent) {
// mails is an array of mail object, index start at 0
// numberOfMailSent is just a counter to know how many mails have been sent
if (index >= mails.length) return numberOfMailSent
const mail = mails[position]
const newMailSent = await sendEmail(mail)
return sendAlerts(mails, index + 1, numberOfMailSent + newMailSent)
}
Any idea where I could be wrong or in some other way send over 100 emails?
source to share
Use pooled SMTP: https://nodemailer.com/smtp/pooled/
If a pool is in use then Nodemailer opens a fixed number of connections and sends the next message after the connection becomes available. This is mostly useful when you have a large number of messages that you want to send in batches, or your ISP only allows a small number of concurrent connections.
source to share