简体   繁体   中英

SendGrid: How to send emails to my contact list using Node.JS?

I'm trying to send daily emails to my SendGrid contact list with Node.JS.

At the moment I'm querying all of my subscribers and looping through them then sending them the email one by one.

The problem with this approach is that SendGrid doesn't let me send 1000 emails at once and throws a rate limit error hence I need to create a 5 seconds delay between each request.

This is what I do at the moment:

verifiedSubscribers.map(async (subscriber, i) => {
  const timer = setTimeout(() => {
    sgMail.send({
      from: 'me@example.com',
      to: subscriber.email,
      subject: 'test',
      text: 'test',
      html: 'test',
    })

    clearTimeout(timer)
  }, 5000 * i)
})

So is there any way to send the emails at once to my contact list?

Your code is setting up a lot of timers that will fire all at once five seconds out.

You may want something like this.

/** await snooze(100) delays for 100 milliseconds */
function snooze(milliseconds) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, milliseconds)
  })
}

async function sendAll (verifiedSubscribers) {
  for (subscriber of verifiedSubscribers) {
    await sgMail.send({ ...  whatever ...} )
    await snooze(100)
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM