0

I need to send an email to many recipients

var recipients = [1@gmail.com, b@gmail.com, c@gmail.com]

I have one template named template1

var templateId = ["237173"];

The text content of one of the block of template vary for every recipient hence the block_content array will be of same size as receipients array respectively

var block_content = ["<h2>HR1213675</h2>","<h2>8923783ER</h2>","<h2>JUIYE34324</h2>"] // respectively for email array

I have [1@gmail.com, b@gmail.com, c@gmail.com, d@gmail.com, e@gmail.com, f@gmail.com ...] many emails subscribed in my campaign1

I tried to send emails to the receipients but this fails

I think I am using incorrect endpint and I dont know how to insert the block_content to the template email and shoot emails uniquely for recipients

Where I am doing wrong?

function sendMailchimpEmail() {
  // Your Mailchimp API Key
  var apiKey = YOUR_API_KEY;
  
  // Your Mailchimp Server URL
  var endpoint = 'https://us2.api.mailchimp.com/3.0/';
 

  // Your Mailchimp API Request Options
  var options = {
    'method': 'POST',
    'Content-Type': 'application/json',
    'headers': {
      'Authorization': 'apikey ' + apiKey
    }
  };

  // Construct the API request body
  var data = {
    'recipients': [
      {
        'email_address': recipients
      }
    ],
    'template': {
      'id': templateId
    }
  };

  // Create and Execute API Request
  var response = UrlFetchApp.fetch(endpoint + '/campaigns', options);
  var json = response.getContentText();
  var payload = JSON.parse(json);

  // Send the email
  UrlFetchApp.fetch('https://us2.api.mailchimp.com/3.0/campaigns/actions/send', options, data);
}
Code Guy
  • 3,059
  • 2
  • 30
  • 74

1 Answers1

-1

This is the scheme i succesfully use. Note that "to" is an array of objects (yo can "to" to multiple emails). Note you can add "cc" and/or in the same way. Just try it, i'm sure you gonna figure out how to port this to your own case.

  var headers = {
    "Authorization" : "Bearer " + SENDGRID_KEY, 
    "Content-Type": "application/json" 
  };
  
  var body =
      {
        "personalizations": [
          {
            "to": [  
              {
                "name":  toName,
                "email": to
              }
            ],
            "subject": subJet
          }
        ],
        "from": {
          "name":  fromName,
          "email": from
        },
        "content": [ 
          {
            "type": "text/html",
            "value": payLoad
          }
        ]
      };
  
  
  var options = {
    'method':'post',
    'headers':headers,
    'payload':JSON.stringify(body)
  };
  
  var response = "OK";
  
  try{
    UrlFetchApp.fetch("https://api.sendgrid.com/v3/mail/send",options);
  }catch(e){
    response = e;
  }
jpp
  • 194
  • 1
  • 7