Sending Bulk Emails 3 Ways With Twilio SendGrid And Node.js
Tags: twilio, node, email, sendgrid
Published: 2019-12-09 23:10:24

---
canonical_url: https://www.twilio.com/blog/sending-bulk-emails-3-ways-sendgrid-nodejs
---

Sending a [single email](https://www.twilio.com/blog/how-to-send-emails-in-javascript-with-sendgrid) is great, but one of the big advantages of email is quickly reaching a wider audience. Today I’ll show you three ways to send bulk emails with Node.js and SendGrid. Just for fun, let’s say you’re a JavaScript developer who works at a donut shop. You need a way of letting the customers who have signed up to your email list know when fresh donuts have come straight out of the oven.

## Prerequisites

- [Node.js and npm](https://nodejs.org/en/#download) installed
- A free SendGrid account - sign up [here](https://signup.sendgrid.com/)
- At least two email addresses, to test things out and make sure they’re working. You can sign up for (multiple) [free Gmail addresses here](https://www.google.com/gmail/about/). Or you can try the old hack of adding a  [+ to your existing Gmail address](https://gmail.googleblog.com/2008/03/2-hidden-ways-to-get-more-from-your.html). Caveat: we ran into some deliverability issues using that hack.

## Setting up your environment

First, create your API key from the [SendGrid dashboard](https://app.sendgrid.com/settings/api_keys). Let’s call it “bulk email.”

![A screenshot of the SendGrid "Create API Key" page. "Full Access" is selected, and the key name is "bulk email".](https://thepracticaldev.s3.amazonaws.com/i/mynikhokz9ddkjkddzww.png)

After clicking “Create & View”, you’ll see your key. Before you close this dialog box, save the key in an [environment variable](https://www.twilio.com/blog/2017/01/how-to-set-environment-variables.html), `SENDGRID_API_KEY`. You won’t be able to get that same key from the SendGrid dashboard again for security reasons.

Run `npm init` to start a new Node.js project. Install the Sendgrid helper library with `npm install @sendgrid/mail`. Create a file called `index.js` and open it in your editor of choice.

## Method 1: sendMultiple

The most straightforward way to send bulk emails is to have an array of addresses in the `to` field, and then call `sendMultiple` with a single message object.

Copy this code into `index.js` and replace the emails in the to array with your email addresses.

```javascript
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const msg = {
  to: ['example1@mail.com', 'example2@mail.com'], // replace these with your email addresses
  from: 'Sadie Miller <sadie@thebigdonut.party>',
  subject: '🍩 Donuts, at the big donut 🍩',
  text: 'Fresh donuts are out of the oven. Get them while they’re hot!',
  html: '<p>Fresh donuts are out of the oven. Get them while they’re <em>hot!</em></p>',
};

sgMail.sendMultiple(msg).then(() => {
  console.log('emails sent successfully!');
}).catch(error => {
  console.log(error);
});
```

Run the code by running `node index.js` from the terminal. You should see console output letting you know the script ran successfully, and watch the emails arrive in your inboxes shortly.

![A screenshot of an email from "Sadie Miller" with the subject line "🍩 Donuts, at the big donut 🍩" and a body of "Fresh donuts are out of the oven. Get them while they're hot!"](https://thepracticaldev.s3.amazonaws.com/i/nqixpg4zxabka4tvklf2.png)

The current API rate limit is 1000 emails per request. If your high-throughput, scalable, fault tolerant donut shop has more customers than that you’ll need to split into multiple requests.

Recipients of this email won’t be able to see one another’s email addresses. If you want to send multiple email addresses but keep the recipients addresses visible to one another, use the same code as above but replace `sgMail.sendMultiple` with `sgMail.send`. That said, be careful and **don’t expose your customers’ email addresses unless you have a good use case for doing so**.

## Method 2: personalization

If you’re a good donut shop owner, you’ve been paying attention to your customers. You noticed that Steven really loves bacon flavored donuts.

With personalizations, you can change the emails you send to your customers to make them more, well, personal. Like mentioning their favorite kind of donut in the subject line to entice them to come in.

Replace the code you’ve got in `index.js` with the following:
```javascript
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const msg = {
  personalizations: [
    {
      to: 'example1@mail.com', // replace this with your email address
      subject: 'Did somebody say BACON DONUTS?? 🥓🥓🥓',
    },
    {
      to: 'example2@mail.com', // replace this with your email address
    }
  ],
  from: 'Sadie Miller <sadie@thebigdonut.party>',
  subject: '🍩 Donuts, at the big donut 🍩',
  text: 'Fresh donuts are out of the oven. Get them while they’re hot!',
  html: '<p>Fresh donuts are out of the oven. Get them while they’re <em>hot!</em></p>',
};

sgMail.send(msg).then(() => {
  console.log('emails sent successfully!');
}).catch(error => {
  console.log(error);
});
```

Run `node index.js` on the command line to try it out.

![An email from "Sadie Miller." The subject line is "Did somebody say BACON DONUTS?? 🥓🥓🥓" and the body is "Fresh donuts are out of the oven. Get them while they’re hot!"](https://thepracticaldev.s3.amazonaws.com/i/ymze0iubtkm19egwz9v0.png)

If a personalized subject line isn’t supplied for a particular recipient, we fall back to the default. You should have received one email with a bacon subject line, and one with a generic subject line.

The personalizations API can do more than change the subject line. Here’s the [list of attributes that can currently be personalized](https://sendgrid.com/docs/API_Reference/api_v3.html):

- `subject` - the email subject line.
- `headers` - any headers you want to send with the email.
- `substitutions` -  key/value pairs representing strings that you would like to substitute into an email subject line or body.
- `custom_args` -  any custom arguments you would like to include in your email, that will override substitutions.
- `send_at` -  specifies a particular time you’d like the email to be sent, in Unix timestamp format.

## Method 3: array of message objects

An array of message objects is useful if you need to send multiple different emails with various subject lines, bodies, etc to different recipients. The `.send` method also accepts an array of email message objects. Unlike using an array of addresses in the `to` field, the code below will not cc recipients.

```javascript
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const messages = [
  {
    to: 'example1@mail.com', // replace this with your email address
    from: 'Sadie Miller <sadie@thebigdonut.party>',
    subject: 'We miss you 😭',
    text: 'Get 10% off with coupon code NOMNOMNOM',
    html: '<p>Get 10% off with coupon code <b>NOMNOMNOM</b></p>',
  },
  {
    to: 'example2@mail.com', // replace this with your email address
    from: 'Lars Barriga <lars@thebigdonut.party>',
    subject: 'NEW! Ube rolls 😻',
    text: 'In addition to donuts, we are now selling ube rolls.',
    html: '<p>In addition to donuts, we are now selling ube rolls.</p>',
  },
];

sgMail.send(messages).then(() => {
  console.log('emails sent successfully!');
}).catch(error => {
  console.log(error);
});
```

After running this code, you should see two emails in your inboxes:

![Screenshot of an email from "Lars Barriga." The subject line is "NEW! Ube rolls 😻" and the body is "In addition to donuts, we are now selling ube rolls."](https://thepracticaldev.s3.amazonaws.com/i/heq5dob00qic42jt61qb.png)

![Screenshot of an email from "Sadie Miller." The subject line is "We miss you 😭" and the body is "Get 10% off with coupon code NOMNOMNOM"](https://thepracticaldev.s3.amazonaws.com/i/sf5268o8xk9e5ctvp2pj.png)

## What’s next?

Let’s review what we’ve learned today:

- How to send a single SendGrid emails to multiple recipients
- How to use personalizations to customize emails to multiple recipients
- How to send multiple, different emails to multiple different recipients

Give yourself a reward, you’ve earned it. 🎉 If you’re craving donuts now, sorry not sorry.

The SendGrid API is so full-featured and flexible that it’s impossible to fit everything it can do into one blog post. For the most up to date information, check out the [docs](https://sendgrid.com/docs/API_Reference/api_v3.html). You can also look at the open source code for the [Node.js helper library](https://www.npmjs.com/package/@sendgrid/mail) which is available on [GitHub](https://github.com/sendgrid/sendgrid-nodejs/tree/master/use-cases). Thanks for reading, and happy emailing.