How to send personalized emails to multiple addresses using sendgrid in NodeJS

720 Views Asked by At

I have an array of email addresses and an array of passwords. I want to send each password to its corresponding email address(email at same index) in the body of email. But I don't want to use a loop. Is it possible to use substitution in the email body and then have sendgrid pick a value from the password array for each email address. I know I can construct a personalizations object like so :

personalizations: {to: [{email: "email1"}], substitutions: {"-pwd-": "pwd1"}}

and then use -pwd- in the body of email. But to construct this object I again have to use a loop which I don't want.

1

There are 1 best solutions below

2
Adam Urban On

Haven't tried it out, but according to the SendGrid Docs it should be able.

The given example in the docs (for SendGrid API v3) looks the following way:

{
  "personalizations": [
    {
      "to": [
        {
          "email": "[email protected]",
          "name": "John"
        }
      ],
      "subject": "Example 01",
      "substitutions": {
        "-name-": "John"
      }
    },
    {
      "to": [
        {
          "email": "[email protected]",
          "name": "Jane"
        }
      ],
      "subject": "Example 02",
      "substitutions": {
        "-name-": "Jane"
      }
    },
    {
      "to": [
        {
          "email": "[email protected]",
          "name": "Matt"
        }
      ],
      "subject": "Example 03",
      "substitutions": {
        "-name-": "Matt"
      }
    }
  ],
  "from": {
    "email": "[email protected]",
    "name": "Sender"
  },
  "reply_to": {
    "email": "[email protected]",
    "name": "Sender"
  },
  "subject": "Example",
  "content": [
    {
      "type": "text/plain",
      "value": "Hello -name-,"
    },
    {
      "type": "text/html",
      "value": "Hello -name-,"
    }
  ]
}

By using Dynamic Transactional Templates it should work the same way with handlebars.