I am creating a Google Sheet to send mails using SendGrid.
Below is the code for sending mails with Google Apps Script, but I do not manage to send to multiple recipients. I adapted it from this SO question: Send emails using Sendgrid with google appscript
It works, but it sends an email only to the first element of the list of recipients.
function AutoSend2() {
var SENDGRID_KEY ='MY_KEY';
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Feuille 1");
var numRows = sheet.getLastRow() - 1;
var sheet_ti = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("TEMPLATE_ID");
var data_ti = sheet_ti.getDataRange().getValues();
var template_id = data_ti[0][0];
var data = sheet.getDataRange().getValues();
var headers = {
"Authorization" : "Bearer "+ SENDGRID_KEY,
"Content-Type": "application/json"
}
for (ind_to = 0; ind_to <= 15; ind_to++) {
if (data[0][ind_to] == "EMAILS") {
break;
}
if (ind_to == 15) {
ind_to = -1;
break;
}
}
for (i = 1; i < data.length && i <= numRows; i++) {
var pers = [{
"to": [
{
"email": data[i][ind_to]
}
]
}]
var body =
{
"template_id": template_id,
"from": {
"email": "newsletters@xxx.com",
"name": "XXX"
},
"content": [
{
"type": "text/html",
"value": "XXX"
}
],
"personalizations":
pers
}
var options =
{
'method': 'post',
'headers': headers,
'payload': JSON.stringify(body)
}
var response = UrlFetchApp.fetch("https://api.sendgrid.com/v3/mail/send", options)
}
}
I get this error message :
https://api.sendgrid.com/v3/mail/send. Code renvoyé : 400. Réponse tronquée du serveur : {"errors":[{"message":"Invalid type. Expected: object, given: string.","field":"personalizations.0.to.0","help":"http://sendgrid.com/docs/API_Refer...
Any idea of how to fix this? Thanks.