google-apps-scriptgoogle-calendar-apigoogle-app-invites

Sending multiple Google calendar invites using Google apps script


Following my previous question, I was able to send a Google calendar invite using the script proposed by @Tanaike:

function testNotification(){

         var calendarId = "###";
         var eventId = "###";
         var email = "###@gmail.com"
         addGuestAndSendEmail(calendarId,eventId,email)
       }
           
        function addGuestAndSendEmail(calendarId, eventId, newGuest) {
           Calendar.Events.patch({ attendees: [{ email: newGuest }] }, calendarId, eventId, { sendUpdates: "all" });
    }

However, there is a slight glitch that I am not able to identify. When I try to send invites to multiple email addresses at the same time, it behaves unusually. Here is the new script:

      function SendMultiple(calendarId, eventId) {
    
                newGuests = ["user1@gmail.com","user2@gmail.com"];
                newGuests.forEach(function(e){
                 Utilities.sleep(10000);
                Calendar.Events.patch({ attendees: [{ email: e.toString()}] }, calendarId, eventId, { sendUpdates: "all" });
  });    
}

Output:

when the SendMultiple() function finishes running, it sends 2 invites (event created, event canceled) to user1@gmail.com and 2 invites (event created, event canceled) to user2@gmail.com, I am unable to identify why the event canceled invite is generated using this script. If I interchange the emails in newGuests array:

newGuests = ["user2@gmail.com","user1@gmail.com"];

then it behaves the same, I would appreciate it if you help me identify the issue, thank you


Solution

  • In your script, how about modifying as follows?

    Modified script:

    function SendMultiple(calendarId, eventId) {
      var newGuests = ["user1@gmail.com", "user2@gmail.com"];
      Calendar.Events.patch({ attendees: newGuests.map(email => ({ email })) }, calendarId, eventId, { sendUpdates: "all" });
    }