why isn't google apps script sending invitations - google-apps-script

The Google Apps script ran in a spreadsheet below and everything worked fine except sending the invites. Using sendInvites:true the event is created in the calendar and the guests are added but no email is sent. I have tried it without using the var advancedArgs and same results.
if (eventImported != EVENT_IMPORTED && title != "") { // Prevents importing duplicates
var cal = CalendarApp.openByName('calendarname');
var advancedArgs = {description: details, location: cust, guests:guestlist, sendInvites:true};
cal.createEvent("10% Complete-->"+title, startDate, endDate, {description: details, location: cust, guests:guestlist, sendInvites:true});
sheet.getRange(startcolumn + i, 9).setValue(EVENT_IMPORTED);

The error must be somewhere else, I tested your code in this simplified version and I received the invitation as expected. (I use this option a lot in many scripts without any issue)
Could you show how you get your guest list ? is it a comma separated email list as specified in the documentation ?
function testcal(){
var cal = CalendarApp.getDefaultCalendar()
var advancedArgs = {description: 'details', location: 'here', guests:'serge#xxx.com', sendInvites:true};// change the email adress to a valid one that you have access to (but not your email adress of course !
var startDate = new Date();// now
var endDate = new Date(startDate.setHours(10));// at 10 AM, change this according to time of the day when you (eventually) test it
cal.createEvent("test to delete", startDate, endDate, advancedArgs);
}

I suspect you may be being rate limited somewhere. I had a similar problem and sending emails would work sporadically. I was polling a group of users calendars and when I found enough available at a certain time I would send the invitation to all.
In frustration I added:
Utilities.sleep(30000);
just before I create the event and it works reliably now. You can probably get away with less time, but mine runs on trigger at 2am so I don't care.

I found out that no event invitation is sent to my own email address (although the event is added to my calendar). But event invitations are correctly sent to other guests.

Try Out:
var advancedArgs = {description: details, location: cust,
guests:guestlist, sendInvites:"TRUE"};

Related

Creating calendar event in sheets using Google App Script and want to add attendees

I'm trying to create calendar events in sheets using Google App Script (I'm very new to this). The sheet contains details of the event (date, time, event title, and guest list) as well as the calendar ID (this is a training calendar). I want to make it simple for the end-user to fill in the information on the sheet, click 'schedule now' and the script run and send the events out to all email addresses mentioned in the guest list.
Here is an example of the sheet:
Here is a copy of the code (I found this on the Google Developer website and tried to adapt it to add guests but haven't been able to get it working and really not sure where to go with this. Ideally, I'd like the guest list to come from the sheet and not be written into the code as an option.
function scheduleTraining() {
var spreadsheet = SpreadsheetApp.getActiveSheet();
var calendarId = spreadsheet.getRange("C3").getValue();
var eventCal = CalendarApp.getCalendarById(calendarId);
Logger.log(eventCal)
var signups = spreadsheet.getRange("A5:C20").getValues();
for (x=0; x<signups.length; x++) {
var shift = signups[x];
var startTime = shift[0]
var endTime = shift[1]
var title = shift[2]
eventCal.createEvent(title, startTime, endTime, {
location: 'remote',
description: 'snacks provided',
})
}
}
function onOpen(e) {
SpreadsheetApp.getUi()
.createMenu('Schedule Training')
.addItem('Schedule Now', 'scheduleTraining')
.addToUi();
}
If anyone can help with this or has any ideas on how to do this better, I'm all ears!
Thanks!
Issues:
The dates in your spreadsheet file are strings/texts. You can verify that if you do =isDate(A7). If the latter returns FALSE then you don't have a valid date object. If you see the official documentation you need to pass date objects and not date texts.
Another remark I have is that your range is "A5:C20" but you should start from A7. Row 5 and 6 don't contain the information required, according to your screenshot.
Question based on your comment:
how I can include inviting the guests when it's run
Again according to the documentation, you can add guests using the advanced parameters options and in particular guests:
eventCal.createEvent(title, startTime, endTime, {
location: 'remote',
description: 'snacks provided',
guests: 'test1#gmail.com,test2#gmail.com'
})
guests is a type of string that contains a comma-separated list of email addresses
that should be added as guests.

How do I get my google calendar event's ID into the right format for the Calendar API to read in my script?

I'm trying to write a script that will do both: 1) update an existing event's dates and title on my Google calendar, based on the dates provided in my sheet AND 2) send the updated dates by email to the event's guests (so the event on their calendars is updated).
I was able to successfully update my event's dates and title using CalendarApp.getEventById(eventId). However, I'd really like the event notifications to resend to each guest when the dates of the event have updated. This doesn't seem possible to do using CalendarApp (if it's possible, please tell me how!). After struggling with this in this question, I'm now trying to use Calendar.Events.patch to both update the event and send the update to all the event's guests.
The problem I keep encountering is that the eventId, as logged in my sheet by my createEvent script, is in a format ending in "#google.com." This format is read just fine by CalendarApp, but cannot be read by Calendar.Events.patch. I've tried encoding it to base64, since that seeems to be the format looked for by Calendar.Events.patch, but I think I'm still missing something.
When I run the code below, the error returns "API call to calendar.events.get failed with error: Not Found."
function updateEvent(calendarId, eventId, email) {
var vSS = SpreadsheetApp.getActiveSpreadsheet();
var vS = vSS.getActiveSheet();
var eventId = vS.getRange("R2").getValue(); //R2 is the cell where my eventId is logged
//My attempt to encode my eventId to base64
var base64data = eventId;
var encoded = Utilities.base64Encode(base64data,Utilities.Charset.UTF_8);
var vEventName = vS.getRange("M3").getValue();
var newstartTime = vS.getRange("M5").getValue();
var newendTime = vS.getRange("M6").getValue();
var event = Calendar.Events.get('example#gmail.com', encoded);
if(event.attendees) {
event.attendees.push({
email: email
});
} else {
event.attendees = new Array({email: email});
}
event = Calendar.Events.patch(vEventName, encoded, {
start: newstartTime,
end: newendTime,
sendUpdates: "all"});
}
I suspect the encoded eventId is off a few characters or something, since that seems to be the case when I run the #google.com eventId through this encoding tool. I just don't know enough to fix it.
Please understand that I'm extremely new to writing scripts and I've already been struggling with this issue for well over a week. I think I learned a lot after the last question I posted, since now I have a better understanding of my exact problem, but I still don't know the fix. I'm trying to teach myself how to do this by reading the questions on this website, reading Google's information (which I unfortunately largely don't understand), and watching YouTube videos. If I'm asking too much of the script, please let me know.
You want to retrieve an event using event ID.
You want to update an event and send an email to users.
You want to modify the event name, start and end time of the event.
eventId is 1c0tqtn56c1tdo1i0fus66f53g#google.com which is a text value.
vEventName is Ethiopia Limu which is a text value.
newstartTime is 6/10/2019 which is a date object.
newendTime is 7/30/2019 which is a date object.
If my understanding is correct, how about this modification?
Modification points:
In your script, it seems that the scripts for retrieving the event and updating the event are different. So in this modification, there were separated.
You can see the event at the log, when the script is run.
The event is updated.
About the event ID, you can use 1c0tqtn56c1tdo1i0fus66f53g of 1c0tqtn56c1tdo1i0fus66f53g#google.com as the event ID.
When these are reflected to your script, it becomes as follows.
Modified script:
function updateEvent(calendarId, eventId, email) {
var vSS = SpreadsheetApp.getActiveSpreadsheet();
var vS = vSS.getActiveSheet();
var eventId = vS.getRange("R2").getValue();
var vEventName = vS.getRange("M3").getValue();
var newstartTime = vS.getRange("M5").getValue();
var newendTime = vS.getRange("M6").getValue();
var eid = eventId.split("#")[0]; // Added
// Retrieve event
var event = Calendar.Events.get(calendarId, eid);
if(event.attendees) {
event.attendees.push({
email: email
});
} else {
event.attendees = new Array({email: email});
}
Logger.log(event)
// Update event
var resource = {
start: {dateTime: newstartTime.toISOString()},
end: {dateTime: newendTime.toISOString()},
summary: vEventName,
};
Calendar.Events.patch(resource, calendarId, eid, {sendUpdates: "all"})
}
Note:
If an error related to date and time occurs when the event is updated, please confirm whether newstartTime and newendTime are the date object, respectively.
Reference:
Events: patch

How can I check the availability of an email id in google calender to be shown in google form

I am quite new to google app scripting and looking for best suggestions and lookouts,
I have made a form that creates the meeting event in gogole app script, and I need to add the possibility of checking the availability of any email id I am inviting to the meeting.
The code for creating a meeting invite.
function CreateEvent_( NamedValues )
{
var calendar = CalendarApp.getDefaultCalendar();
var cEvent1 = calendar.createEvent(NamedValues.Subject_Title, new Date(NamedValues.Start_date_time_1), new Date(NamedValues.End_date_time_1), {description: NamedValues.Description_Competency_1+NamedValues.Interview_1_Type, location: NamedValues.Location_1[0], guests: guestList1, sendInvites: true});
}
function OnFormSubmit(e)
{
Logger.log(e.namedValues);
CreateEvent_(e.namedValues );
}
function updateSheet()
{
//code to update sheet
}
How can I include a section where we can check the availablity of any email id we are including in the meeting
Thanks in advance
I never used it but if I read the documentation on Advanced Calendar Service and particularly the Freebusy page it seems that you can get the availability of a group or a single user.
If you come to a working solution I would be happy to see it.
Edit: see also this post with a sample code Why does the 'Free/Busy' time for Google Calendar API come back 'Undefined'?

Inviting guests to a "Quick Add" Google Calendar event

I am trying to improve the functionality of the "Quick Add" feature in Google Calendar. Quick Add is the feature that is normally accessed by going to Google Calendar and clicking the down arrow next to the red "Create" button (see image: http://s2.postimg.org/95zxshivt/calendar_screenshot.png).
The functionality I am trying to achieve is to allow the user to invite guests to the newly created Calendar event using keywords in what they type in the Quick Add box. For example, if the user uses the Quick Add box to add an event by entering the text Eat pizza tomorrow at 3pm with michelle#gmail.com and john#gmail.com, Google Calendar adds a new event with the title Eat pizza with michelle#gmail.com and john#gmail.com at 3pm the next day, like it is supposed to. I want to go a step further by having Google also send out two Calendar invites to the newly created event: one for michelle#gmail.com and the other to john#gmail.com.
I appreciate your advice on this topic. I am trying to understand what the best approach is:
Use a trigger with Google Apps Script to catch when the user has added a Calendar event. The trigger will access the title of the event, pick out any e-mail addresses present in the title, and send an invitation to the newly created event to each of those e-mail addresses.
Use a Chrome extension to have the user enter the string that they normally would type into the Quick Add box by clicking on the extension's icon in the Chrome browser. The extension would pick the e-mail addresses out of what the user types in, use createEventFromDescription(description) on the user's input to create the event, and then send an invitation to the newly created event to each of those e-mail addresses.
Please let me know what you think. I would greatly appreciate your ideas.
Lucy
As you probably know, there is not trigger source linked to the creation of an event from the Calendar Ui.
You have indeed 2 possibilities :
encode the event using a dedicated Ui (a chrome extension or a standalone webapp) that would take care of sending the invitations but that would probably not meet the initial requirement you described as "expanding the capabilities os the quickAdd features"
Find a way to detect an event creation and automatically send invitations from its content.
This last possibility is perfectly doable using a timer trigger that monitors your calendar and detects any new event (by comparing a list stored somewhere to the actual calendar content).
I have made such an app for a different purpose and it works nicely but there are a few difficulties you should be aware of.
When storing the events in scriptProperties (it's probably the best place to go) you have a limited amount of storage size available so you must know how much event you will be able to handle.
Any change in an event like adding a detail or rectifying a typo will re-trigger the invitation process and send the invitation again. Although this can probably be avoided but it would be quite complex.
When the script runs right after an event end, the comparison detects an change because one event is missing (from the script pov) so it could send a mail to cancel the event (if you had chosen to implement that functionality of course but I guess it's a "must have"). It might be a bit tricky to handle that situation... (compare event end time to actual time when the trigger fires the script, could be a matter of milliseconds ;-).
Apart from these difficulties, the general idea is as follow :
create a timer trigger to run every hour or so
store every event in this calendar in script Properties (or eventually in a spreadsheet) starting from the present date and ending in a few days (not too far ahead because it wouldn't make sense to send invites for an event happening next year)
compare the list with the calendar content
grab every "new" events and extract email address from the description (using regex for example or string manipulation)
send the invitations (that's the easy part)
This workflow works but it might be a bit fragile in the comparison and in the email detection.
EDIT
Since this was an interesting subject (IMHO) and that I thought I could use efficiently (now that I switched to english in my calendar UI ;-D) I wrote a code to achieve it...
I embedded the code in a spreadsheet to simplify the processsing and the storage of the events in the many calendars I own.
This spreadsheet is viewable here and if you make a copy of it you'll be able to run the code.
I setup a timer trigger that runs the autoCheckAllCal function every hour and it seems to work without any issue.
Tell me what you think.
The full code is reproduced below, it gets data from the calendar, checks if the event has guests and if not it checks the title for any valid email address (one or more) and sends the invitations automatically.
I used a regex to extract emails from the title string (this regex was borrowed from an answer on SO since I'm not good enough at this !)
note : setup an onOpen trigger for myOnOpen (because of global var declaration using SS service)
// update the ID below to your copy ID and run the Callist() function to get the calendars ID on first sheet.
//set up an onOpen trigger for the myOnOpen function
var ss = SpreadsheetApp.openById('1xDOaoSl3HbkS95cj8Jl-82rdiui7G0sFz96PIO6iVF4');// this spreadsheet
var calNamesSheet = ss.getSheetByName('calNames');
var calList = calNamesSheet.getDataRange().getValues();
function MyOnOpen() {
var menuEntries = [ {name: "Lauch autoTest", functionName: "autoCheckAllCals"},
{name: "delete created sheets", functionName: "delsheets"}
];
ss.addMenu("Tracking utilities",menuEntries);//
}
function autoCheckAllCals(){
var today = new Date(); // now
var startDate = new Date(today.setHours(0,0,0,0));// today # 0 AM
var endDate = new Date(new Date(startDate).setDate(startDate.getDate()+7)); // adjust time frame to read here = 7 days
for(var nn=0;nn<calList.length;nn++){
var logArray = new Array();
logArray.push(['Calendar + Title','Description','Start','End','Location','Creators','Date Created','Duration','Guests']);
var calName = calList[nn][0];
var calId = calList[nn][1];
var Calendar = CalendarApp.getCalendarById(calId);
var events = Calendar.getEvents(startDate , endDate);
if (events[0]) {
for (var i = 0; i < events.length; i++) {
var row = new Array();
row.push(calName +' : '+events[i].getTitle());
row.push(events[i].getDescription());
row.push(Utilities.formatDate(events[i].getStartTime(), Session.getScriptTimeZone(), "MMM-dd-yy")+' # ' +Utilities.formatDate(events[i].getStartTime(), Session.getScriptTimeZone(), "HH:mm"));
row.push(Utilities.formatDate(events[i].getEndTime(), Session.getScriptTimeZone(), "MMM-dd-yy")+' # ' +Utilities.formatDate(events[i].getEndTime(), Session.getScriptTimeZone(), "HH:mm"));
row.push(events[i].getLocation());
row.push(events[i].getCreators().join());
row.push('on '+Utilities.formatDate(events[i].getLastUpdated(), Session.getScriptTimeZone(), "MMM-dd-yyyy"));
row.push(((events[i].getEndTime() - events[i].getStartTime()) / 3600000)+' hours');//duration
var inviteList = checkInvites(events[i]);
if (inviteList.length==0){ // if guests were found in checkInvites() then don't read it from event since checkInvites() added them to the cal but this event is not yet updated
var list = events[i].getGuestList();
for(n=0;n<list.length;++n){inviteList.push(list[n].getEmail())};
}else{
for(var n in inviteList){
events[i].addGuest(inviteList[n]);
}
}
row.push(inviteList.join(', '));
logArray.push(row);
}
}
// Logger.log(logArray);
if(logArray.length==0){continue};
try{
var sheetToWrite = ss.insertSheet(calName,ss.getNumSheets());// create sheet if doesn't exist
}catch(err){
var sheetToWrite = ss.getSheetByName(calName);// else open it
}
sheetToWrite.getRange(1,1,logArray.length,logArray[0].length).setValues(logArray).setHorizontalAlignment('left'); // enhance formating
sheetToWrite.getRange(1,1,1,logArray[0].length).setBackground('#EEA').setBorder(true,true,true,true,true,true).setHorizontalAlignment('left').setFontSize(12);
for(var w in logArray[0]){
sheetToWrite.setColumnWidth(Number(w)+1,180);
}
}
}
function checkInvites(event){
var email = []
var title = event.getTitle();
if(title.indexOf('#')==-1){return email};
email = title.match(/([\w-\.]+)#((?:[\w]+\.)+)([a-zA-Z]{2,4})/g);
Logger.log('email var = '+email);
return email;
}
function delsheets(){
var numbofsheet = ss.getNumSheets();// check how many sheets in the spreadsheet
for (var pa=numbofsheet-1;pa>0;pa--){
ss.setActiveSheet(ss.getSheets()[pa]);
if(ss.getSheets()[pa].getSheetName()!='calNames'){
ss.deleteActiveSheet(); // delete sheets begining with the last one
Utilities.sleep(400);
}
}
SpreadsheetApp.flush();
}
// This small function is to get the list of calendar names & Ids that you have access to, please edit the calNames sheet to keep only the ones you want to monitor (without empty rows).
function Callist(){
calNamesSheet.getDataRange().clearContent();
var list = new Array();
var store = new Array();
list = CalendarApp.getAllCalendars()
for (n=0;n<list.length;++n){
var name = list[n].getName() ;
var id = list[n].getId() ;
store.push( [name,id])
}
calNamesSheet.getRange(1,1,store.length,store[0].length).setValues(store);
}
// Serge insas - 08-2014

EventGuest getName() method not working

I just started coding with Google Apps Script.
I tried to write a simple program to pull in events from my calendar and email all the guests in these events.
I have run into 2 problems:
the getName() method returns the guest's email address and not name, even though the name is defined in my Google contacts. (Also, if no name is defined, according to the documentation, it would return null).
I can't seem to use the getCalendarsByName method. getCalendarByID is working correctly, but the getCalendarsByName method doesn't return the calendar wanted. I've also tried getOwnedCalendarsByName, but that doesn't work either.
Would appreciate any help from anyone.
Update at 7/1 3.30pm: Thanks to #Serge insas, the second problem has been solved.
However, the first problem remains. Here's the code:
function myFunction() {
var calendar = CalendarApp.getCalendarsByName('Test Calendar');
Logger.log(calendar[0].getName());
var today = new Date(); // get today's date
Logger.log(today.toLocaleString());
var endDate = new Date();
endDate.setDate(today.getDate() +7); // set nextWeek's date to 7 days from today
Logger.log(endDate.toLocaleString());
var testEvents = calendar[0].getEvents(today, endDate);
Logger.log(testEvents[0].getTitle());
var guests = testEvents[0].getGuestList();
Logger.log(guests[0].getName());
}
Here is the Log output:
Test Calendar
July 1, 2012 3:27:58 PM EDT
July 8, 2012 3:27:58 PM EDT
Test Event 1
duytri.nguyen07#gmail.com
The last line is my email other email address, even though it has been named in my contacts.
The method getCalendarsByName() returns an array (that's why there is an 's' on Calendars), did you take this into account in your code by adding [0] behind it (assuming you have only one Cal with this name or that you want its first occurrence) ?
It would be easier to help you if you provide some code you are using.
(Concerning the guestName, same comment : please provide the code you are using.)
EDIT : thanks for the code. It seems you're right, it looks like an issue ;-/
since the guest must be in the contact list to be able to get his name I guess you could use the contact service to get the guest name... as a workaround... I'll try and let you know...
This should work but - I don't know why - it hangs without any result... maybe you could give it a try ?
var testEvents = calendar[0].getEvents(today, endDate);
Logger.log(testEvents[0].getTitle());
var guests = testEvents[0].getGuestList();
var guestmail = guests[0].getEmail();
Logger.log(guestmail);
var contact = ContactsApp.getContact(guestmail);
var name = contact.getFullName();
Logger.log(guestmail+' '+name);
ContactsApp is tricky, it can only search in Contacts of user running script, not in global one. In administrator account still havn't access to global contact list.