Send Grid: Send 1 Email Many Recipients

node v10.24.1
version: 1.0.0
endpointsharetweet
Below you will find an example of how to send an email to multiple recipients using SendGrid's v3 API via NodeJs. There are a few steps in order to run this example: 1. Get a sendgrid API Key 2. Add the API key to the code below (replace 'process.env.SENDGRID_API_KEY' with your api key) (2.a) Even better create a runkit account and add the SendGrid API Key to your env vars and you'll be able to run the code below as is. 3. Replace the emails with the emails your would like to use 4. Hit run!! 🙌
const sgMail = require('@sendgrid/mail') sgMail.setApiKey(process.env.SENDGRID_API_KEY) // Declare the content we'll use for the email const FROM_EMAIL = 'example@example.io' // <-- Replace with your email const subject = 'Test Email Subject' const body = '<p>Hello HTML world!</p>' const recipients = ['alice@example.com', 'bob@example.com'] // <-- Add your email(s) here to test // Create the personalizations object that will be passed to our message object let personalizations = [{ to: [], subject }] // Iterate over our recipients and add them to the personalizations object for (let index in recipients) { personalizations[0].to[index] = { email: recipients[index] } } /* This is what the object will look like { personalizations: [{ to: [ {email: "alice@example.com"}, {email: "bob@example.com"}, ], subject: "Test Email Subject" }] } */ // Create our message object and pass in the previously created personalizations object const msg = { personalizations, from: FROM_EMAIL, html: body, } // Log to see what our message object looks like console.log(msg) // Send the email, if success log it, else log the error message sgMail.send(msg) .then(() => console.log('Mail sent successfully')) .catch(error => console.error(error.toString()))
If you want to send to mulitple recipents but not allow those receipents to see each other do the following:
// Create the personalizations object that will be passed to our message object personalizations = [] // Iterate over our recipients and add them to the personalizations object for (let index in recipients) { personalizations[index] = { to: recipients[index], subject} } /* This is what the object will look like { personalizations: [ { to: "alice@example.com", subject: "Test Email Subject" }, { to: "bob@example.com", subject: "Test Email Subject" } ] } */ // Redefine the personalizations object msg.personalizations = personalizations // Log to see what our message object looks like console.log(msg) // Send the email, if success log it, else log the error message sgMail.send(msg) .then(() => console.log('Mail sent successfully')) .catch(error => console.error(error.toString()))
Loading…

no comments

    sign in to comment