If you have tried to seamlessly subscribe a user to a Google Calendar as part of an automation workflow in Google Apps Script and discovered that all that happens is that the user gets an automated email request to join, and then it is up to them to accept the calendar invitation to add it to their live calendar list, you’re in the right place.
While providing an invitation gateway makes a lot of sense for Google Workspace consumer(free) accounts where you don’t want strangers to subscribe you to calendars that you don’t want to be a member of, it can be a little frustrating for Google Workspace business and organisations that need users to see a particular calendar.
You’ve probably experienced this, but you can’t always rely on your users to accept these invitations to add a calendar. Then down the track, the user is left scratching their head wondering why they are not getting the calendar events like everyone else.
Table of Contents
Some reasons why you might need to force subscribe a user to a calendar
Think of it this way, imagine you’ve just started work at your new company and as a part of your onboarding process, you’ve accepted an invite to your new Google Workspace domain email and now have a bunch of calendar invites to accept. Plus learn everything you need to about the job. You’re likely to forget.
What about if you are transferring to a new branch in the company or your manager created a new Google Group for you to work under and they have shared a calendar to a Group. Well, guess what? You won’t even get an email to invite you to the group. You won’t even know you are a member.
What about if you need to add new students to classes and each class shares a classroom calendar. Can you expect all the little darlings to accept the calendar invite?
What you’ll need.
In this tutorial, we will assume that you are working on a Google Workspace Domain (paid account) and that you are on speaking terms with your Google Workspace Super Admin (Hint! Snacks are their weakness!)
Force subscribing users to a Google Calendar isn’t as easy as it used to be. Before we even write our code we will need to:
- Create or assign a Google Cloud Project.
- Create a Service Account.
- Supplicate yourself to your Google Workspace Super Admin and request Domain-wide Delegation of Authority for your project.
- Add the service account JSON to your script.
- Add an OAuth library to your script.
This means traversing the Dark Woods of Google known as the Google Cloud Console. Don’t worry, I will step you through the process with instructions and images and get you back to the safety of your trusty Google Apps Script IDE so that we can finally write some code.
Set up
The first thing we need to do is to create a new Google Apps Script project.
Head over your script.google.com and create a stand-alone project and give it a title and save.
Adding the OAuth2 Library
We’ll also be using the OAuth2 for Apps Script library for our project. This is an open-source library gifted from Google Workspace devs and updates and supported by the community.
To add the library copy the following ID:
1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF
In your Apps Script IDE on the left sidebar select the +
next to the Libraries header (1). A popup dialogue will appear. Paste in the ID (2).
Select Lookup (3). If you pasted in the ID successfully, you’ll see a version appear along with a suggested identifier.
Select Add (4). The dialogue will close and you should see the library appear in your Libraries list in the sidebar (5).
Creating A Service Account
Creating a Google Cloud service account will allow us to impersonate a user in our domain so that we can programmatically accept and display a calendar after it has been shared with them.
The service account will generate a custom email address along with credentials in JSON form for you to use to call the service account in your script.
Time to head over to the Google Cloud Console. Yeah, I know scary stuff. Take a breath and we will do this together.
Let’s go!
Link to: Google Cloud Console✨✨✨
Select a Google Cloud Project
In the top menu bar, you will see a selected account (The console will usually open to the last project you were working on). If you are happy to work in this project skip to the next bit.
Click on the project name and a dialogue will appear.
Either select an existing account or create a NEW PROJECT.
If you are creating a new project, you will be navigated to a new page. All you need to do here is to create a name for your project (1), ensure that your organisation and locations are pointed to the domain you are working in and then hit Create (3).
You will then be navigated to your new project dashboard.
Note! You do not need to connect your Google Apps Script project to the Google Cloud project. They can run independently.
Get to the service account page
You can get to the service account page in a number of ways:
- In the sidebar, select IAM and admin > Service accounts
- From the search menu at the top type “Service Accounts”.
- Or via this link (https://console.cloud.google.com/iam-admin/serviceaccounts) and then select your project.
Create the service account
On the Service Account sub-menu bar select Create Service Account.
Add the title you will give the service account (1). Note that you will see the Service Account ID update automatically (2). You can change it but we will leave it. Also, note there that you can see your service account email address being built too.
Next, add a description so you know in 3 months time what on earth you were building here (3).
Finally, select Create and Continue (4).
Next, you will be given the option to “Grant this service account access to the project”. Now that you have created your very own non-human entity in the form of a service account (beep bop boop blerg!), you can assign the account certain roles with certain permission in the connected project.
Let’s hold off on the A.I. apocalypse for now and skip this step.
Lastly, you can grant access to what users or groups can impersonate or access the service account. This is useful if you only want a select group to have access. If we leave it blank it will stay open for anyone who has access to the script to run the service account to be able to use it. Let’s skip this for this tutorial.
Get the Service Account key
After you click done you will be sent back to the main Service Accounts page of your project. We’ll need to create an account key.
Click on the vertical ellipses on the right our your new service account. Select Manager keys.
A new page will appear. Select Add key > Create new key.
A dialogue box will pop up. Ensure that JSON is selected and then select create. Your JSON key will now be downloaded and another dialogue box will appear. Select Close.
Go ahead and open up the JSON file you downloaded. Select the contents and head over to your Google Apps Script project.
Create a new *.gs
file and name it ‘AUTH’. Set a global constant variable as AUTH
and paste in your JSON data. Your AUTH.gs file should look a little like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
/** * This the Service Key data generated from the Google Cloud Console. * If this is a script just for you, it is fine to keep it like this, otherwise, * make sure you hide it in your PropertySerivce.getUserProperites() */ const AUTH = { "type": "service_account", "project_id": "handsome-goat-5555555", "private_key_id": "dd892b7d099eabe5bbe2bffcf0532f6b05e95b6c", "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADA2BgkqhkiG9w0BAQEFAASCBKYwggSiAgrAAoIBAQ3G+6jN1QVDsRg7\n0R22xfKrbsFXxHQdqv3hQnSAYIjE/eOOUkvQJ64zzsJj3RazkcqE0TRv4OmII6p7\n0nF1MqCBhg9IEAfxAaqFotS2xO8ucxT3TZGsaoNw9iY4zsAY+z7KLnXMlOJB1a6R\nia5FvyNIgJgVNrUovasdG6Y4YZN+kZtYM8tHJLvJYfKmtEas4K0hzL6lzbg6VU1b\noRulfH1y6Gq2BFK2Nsi2V3EwUMbmjo44XRdu95pnuQ9Pd4es8jsDd8GY3KnWt1a7\nMNhBcBxsTtkoSaPIEuFlGJ5s3KOgypN7uI+EJ+wHUVF9Th7SuKjrZQI6iGJGYcTW\nrdVh/nqpAgMBAAECggEAC0dT338BJZrSj4z1kqQPlstU6CR+H0x+UigfW+q1AuDD\n9sxhkU7/e0y3aWi70N1JsrdYThCs8rcoM5ht6oEEcE4nULomL7kupKPqaisiYRs0\nkUVl+qYbvYCTyQNdgbjckkA3j5SRIzcbkwWSDjneVNyJ2Jvtny3Z8mCxDtz4Wgbp\nhTFVhI0Tg6PRS4qAveoW+quPYFfJuFsNG+hEcJzLCJ73mPxbiFHygbbpoz6BSgFL\nQbG4ZRF7KA1U4++njvCzFfDvWkrfwrlh96oiQ4AiWYRQQosOn7fTgO+SCr7BLps+\n+56Y+he1kzJKnUVdnQxYwwnqaMsy6PsTtAVL92ogkQKBgQC+QR4WpGSYo94rMj4U\n/utQz+EYmNqTf161rfR7VACSShsgouOXvCdCUQlrtQBbv/oEmQvBGuWBTFpUtFO6\nV4ndbIGx7oZZKj2yYPBp7iqUw2Z6jV/oAo5pjUIOwoHftBVHHcL4/OsU0rPyBb4N\nm3GjYFotcBaA+cV4wQe8F+8sEwKBgQC1oPSq0t/sgnvhqiO2/UzVdYS0RFcXQoAn\nh0aCW4Y4UshqzTFZVQ80sYiU/sRVD6VO88uJP5mpNeah3PAG/qDuY7kKF3CV+abc\n9sOc/5JMraUnfoVytnFuRUZvQQLhODw8hnbGjfAABa89dDKe2a/YgWFX78Trw0Lh\nWds07oUd0wKBgBi9SvZSxin7FQa079G3HE5T2cdjCPkpFN23ExV+ZNyg+koSJFo0\nwz4iX4E79iH4IsC6Tgb8Ql+/1/cvw7t1ap36YBsNEzdBAOjTJjAAIlVZ21eQTqpS\nusYK8k4FO5olRqcKvbG24bLBe1i7Wm1Wiz5dZxyFeMeosv7yytiwnA81AoGAO2ss\nn7XdC8KkRG8kv/id6jdH8rFozHM0+bmHl53ZixOJ/WajflYVY2exBw1RrYTw0mNv\ncrcbzf+UM9/TpnYmr9Zv8p04d9f0ftU7qWDy36MTJJh/j8ef1DNVl4/tIUEEc8iJ\nkutcWKWDbtdUuCL/JBUvg1UtVvPKLW74B5kAc4ECgYAGKe8BjnrK/2yqAQM6tyAD\nadeqxlsAynZpJUzRkE/X16+u18M8AMUqXd1r2D3iFppcGQTSqXnH4p4Jg5uAZE46\n/ZUkjSU2AwuJo0IrJO/aeBDXduwtptT7BuR5XoYABEW98KUu3lfmqh37CAH8vZ1o\nGMtPwrNMkxejm4IhtomCcA==\n-----END PRIVATE KEY-----\n", "client_email": "sub-to-calendar@handsome-goat-5555555.iam.gserviceaccount.com", "client_id": "100394991316082213951", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/sub-to-calendar%40handsome-goat-5555555.iam.gserviceaccount.com" } //###OBVIOUSLY FAKE CREDENTIALS - ADD YOUR OWN HERE### |
Save your apps script project and head back to the Service Account cloud console.
Add the Calendar API & Scope
Add the Calendar API to the project
Next, we need to add the Calendar API to the service account project.
In the search menu of your Google Cloud console type “Calendar API” (1). It should be the first option that comes up. Give it a good old click (2)
You should now see the Calendar API page. Select Enable.
Get the Calendar Scopes
We also need the authorisation scopes for our calendar project. We can find them by searching the Google API scope lists under the Calendar API. Or copy and paste the scope below into a comment in your Google Apps Script project for now:
// https://www.googleapis.com/auth/calendar
Get Domain-wide Delegation of Authority for your project
Now it’s time to make friends with your favourite Google Workspace super administrator (Remember the snacks!). If that’s you, well it’s time to reconcile that self-loathing and re-friend yourself, you amazing, beautiful human! 🐐♥
Domain-wide delegation of authority allows apps to access user data or act on a user’s behalf to carry out an action. For our tutorial, we want to accept a calendar from us, the dev, and add it to their calendar list.
You will need access to the Admin console to authorise your Service Account for this. Click on the link below to get there:
In the sidebar menu select Security > Access and data control > API controls. Or use this link:
Scroll down the page to the Domain Wide Delegation section and select Manager Domain Wide Delegation.
Next, select Add new and a dialogue box will appear (1).
You can find the Client ID in the JSON file that you downloaded and put into the variable AUTH
in your ‘AUTH.gs’ file. In our example file above you can find it on line 12 as 100394991316082213951
(2):
1 2 3 4 5 6 7 8 9 |
const AUTH = { //### "client_id": "100394991316082213951", //### } |
Copy and paste in your scope that you saved previously: https://www.googleapis.com/auth/calendar
(3)
Then hit Authorise (4).
You should see your new API client added to your list:
You are all done here. Now go ahead and close the Admin Console and head back to your Google Apps Script project, because guess what? It is time to code. Yay!!!!!
Note! The layout and navigation of certain parts of the Google Workspace Admin Console can change quite regularly I’ve noticed over the years. Even at the time of writing this, I noticed that Google’s documentation on the topic was a little out of date. You may have to bounce from this tutorial to Googles docs or search around on your own to figure out the updated locations. It shouldn’t be too hard to figure out.
The Code…finally!!!
We’ve finally made it to the part we love the most, the code. Here is the full code below with an example runsies()
function to run the code that you can copy, paste and update into your own project.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
/** * Example run function that set the self, user and calendard id variables * and then shares and adds the calendard to the the selected user's calendar list. */ function runsies(){ const user = "targetUser@yagisanatode.com"; const calendar = 'e_vhnj1arsvt7t1vve2klu28n5kg@group.calendar.google.com'; const me = Session.getActiveUser().getEmail(); shareCalendar(calendar, me, user); addCalendarToUserList(user, calendar); } /** * Calls the OAuth2 library that will generate our access token. * @link https://github.com/googleworkspace/apps-script-oauth2 * * @param{string} user - user email. * @returns{Object} OAuth2 class methods */ function getOAuthService(user) { return OAuth2.createService('Service Account') .setTokenUrl('https://accounts.google.com/o/oauth2/token') .setPrivateKey(AUTH.private_key) .setIssuer(AUTH.client_email) .setSubject(user) .setPropertyStore(PropertiesService.getScriptProperties()) .setParam('access_type', 'offline') .setScope('https://www.googleapis.com/auth/calendar'); } /** * Share the calendar with the user. * You will be acting under your own email for this to share * your calendar with the user. * @param{string} calId - The calendar ID to be shared. * @param{string} me - Your email. * @param{string} user - the user's email. * @returns {Object} Returns the calendar object of ACL request. */ function shareCalendar(calId, me, user){ let service = getOAuthService(me); service.reset(); if (service.hasAccess()) { content = JSON.stringify({ 'role':'reader', 'scope':{ 'type':'user', 'value':user } }); const endPoint = `https://www.googleapis.com/calendar/v3/calendars/${calId}/acl`; const response = UrlFetchApp.fetch(endPoint, { method:'POST', headers: { "Content-type": "application/json", "Authorization": 'Bearer ' + service.getAccessToken(), }, payload: content }); console.log(response.getContentText()) return response.getContentText(); } }; /** * Add the calendar to the the users calendar list and * select the calendar. * your calendar with the user. * @param{string} calId - The calendar ID to be shared. * @param{string} user - the user's email. * @returns{Object} Containing details of the added calendar. */ function addCalendarToUserList(user, calendar) { let service = getOAuthService(user); service.reset(); if (service.hasAccess()) { const content = JSON.stringify({ 'id':calendar, 'hidden':false, 'selected': true }); const endPoint = 'https://www.googleapis.com/calendar/v3/users/me/calendarList'; const response = UrlFetchApp.fetch(endPoint, { method:'POST', headers: { "Content-type": "application/json", "Authorization": 'Bearer ' + service.getAccessToken(), }, payload: content }); console.log(response.getContentText()); return response.getContentText(); }; }; |
The script basically runs a two-step process.
First, we run the shareCalendar()
function to share our calendar from our list of calendars with the selected user.
Second, we assume the selected user’s account and accept the subscription invite to the calendar and display it in their calendar list.
Before running the code out in the wild it is probably a good idea to test it on a dummy user account different from your own or an account of someone who is happy to be your test user.
Need help with Google Workspace development?
Go something to solve bigger than Chat GPT?
I can help you with all of your Google Workspace development needs, from custom app development to integrations and security. I have a proven track record of success in helping businesses of all sizes get the most out of Google Workspace.
Schedule a free consultation today to discuss your needs and get started or learn more about our services here.
runsies()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
/** * Example run function that set the self, user and calendard id variables * and then shares and adds the calendard to the the selected user's calendar list. */ function runsies(){ const user = "targetUser@yagisanatode.com"; const calendar = 'e_vhnj1arsvt7t1vve2klu28n5kg@group.calendar.google.com'; const me = Session.getActiveUser().getEmail(); shareCalendar(calendar, me, user); addCalendarToUserList(user, calendar); }; |
The runsies()
function is an example function that runs the function to share the calendar with the user and then runs the function to add the calendar to the user’s calendar list.
We need to set 3 main variables for this project:
- The user’s email.
- The calendar that we want to share. To find the calendar email (kinda looks like a service account doesn’t is 😉) go to your Google Calendar and select the calendar that you want to share by clicking on the 3 vertical ellipses that appear when you hover over it. Then select Settings and sharing.
Select Integratecalendar(1). You will find the id under Calendar ID (2).
- me, my email: This is the email of the user running the script. We use the Google Apps Script Sessions class to get the active user and then apply the
getEmail()
method to get their email. This saves having to re-enter the person’s email each time we run the script.
Next, we run the shareCalendar(calendar, me, user)
function which will share the selected calendar with the user. Once the calendar is shared, we run the addCalendarToUserList(user, calendar)
function.
getOAuthService(user)
The getOAuthService(user)
function calls our OAuth2 library with our selected parameters so that we can assume our service accounts identity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/** * Calls the OAuth2 library that will generate our access token. * @link https://github.com/googleworkspace/apps-script-oauth2 * * @param{string} user - user email. * @returns{Object} OAuth2 class methods */ function getOAuthService(user) { return OAuth2.createService('Service Account') .setTokenUrl('https://accounts.google.com/o/oauth2/token') .setPrivateKey(AUTH.private_key) .setIssuer(AUTH.client_email) .setSubject(user) .setPropertyStore(PropertiesService.getScriptProperties()) .setParam('access_type', 'offline') .setScope('https://www.googleapis.com/auth/calendar'); } |
The function takes the user whose identity that we will assume as an argument.
We run this function two times for our project from:
- shareCalendar() – Here the user is our own account or the variable we defined as
me
. So that we can assume our own account. - addCalendarToUserList() – Here the user argument is the user to who we wish to add our calendar too.
Note that the private key and the issuer on lines 11 and 12 are both collected from our AUTH
object in our ‘AUTH.gs’ file.
You can also see that the subject on line 13 is set to our user
email parameter.
shareCalendar(calId, me, user)
The shareCalendar()
function assumes the active user account and then sends a post request to the Google Calendar API to add a new user to the selected calendar with the role, ‘reader’.
Note! You could use the inbuild Calendar API advance service and not worry about calling the getOAuthService(me) function here, but I decided for a bit of consistency and to better show how the service account works to use the service account. You can find an example of this in a previous tutorial on this topic here:
https://yagisanatode.com/2019/09/21/google-apps-script-how-force-subscribe-google-group-members-to-a-google-calendar-for-g-suite/
This function takes 3 arguments:
calId
– the calendar ID.me
– the currently active user running the script.user
– the user who the active user wants to share their calendar with.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
/** * Share the calendar with the user. * You will be acting under your own email for this to share * your calendar with the user. * @param{string} calId - The calendar ID to be shared. * @param{string} me - Your email. * @param{string} user - the user's email. * @returns {Object} Returns the calendar object of ACL request. */ function shareCalendar(calId, me, user){ let service = getOAuthService(me); service.reset(); if (service.hasAccess()) { content = JSON.stringify({ 'role':'reader', 'scope':{ 'type':'user', 'value':user } }); const endPoint = `https://www.googleapis.com/calendar/v3/calendars/${calId}/acl`; const response = UrlFetchApp.fetch(endPoint, { method:'POST', headers: { "Content-type": "application/json", "Authorization": 'Bearer ' + service.getAccessToken(), }, payload: content }); console.log(response.getContentText()) return response.getContentText(); } }; |
Set up the service account
Our first task is to create a new instance of our getOAuthService(me)
(This is done behind the scenes in the OAuth library). Note here that we assume the me
variable to act as the user running the script. Line 11
After we reset the service (Line 12), effectively flushing the service’s stored data, we check to see that we have access to our service account before setting up to send our request to the Google Calendar API (Line 14).
The Google Calendar API – ACL
To assign access privileges to a calendar we will post to the aptly name Access Control List or ACL method.
This method is called from the HTTP request:
https://www.googleapis.com/calendar/v3/calendars/${calId}/acl
Here we add our calendar id from our calId
parameter and assigned it to our endPoint function. Line 23
The request will require a set of header information that includes the content type which will be in JSON format (Line 28) and the Authorisation. The authorisation details are generated for us by the OAuth library that we assigned to our service variable. We call the getAccessToken()
of this library to display the access token here. Line 29
The request also takes a payload containing a JSON object with the properties that we wish to change. If you look up at lines 16 to 19, you can see that we have set the role to have ‘reader’ access only (Line 16), then assigned our user email to the scope as a user (not a group email).
Fetching the HTTP request
On line 25, we use the fetch() method in the Google Apps Script UrlFetchApp class to send our HTTP request to the Calendar API.
The first argument is our HTTP request URL in the endPoint
variable.
The second argument is an object containing our method (POST), headers, and payload for our request.
When this fetch request is made and is successful it will return a JSON object containing a summary of the changes that will look similar to this:
1 2 3 4 5 6 7 8 9 10 |
{ "kind": "calendar#aclRule", "etag": "\"00002648956775379000\"", "id": "user:targetUser@yagisanatode.com", "scope": { "type": "user", "value": "targetUser@yagisanatode.com" }, "role": "reader" } |
We have logged this just out of interest here and you could delete the console log if you wish. We have also returned this response out of the shareCalendar()
function should you wish to use it for something else.
Bonus! Remove Notification email for user
If, for example, you are setting up onboarding for a new staff member or a new year calendar set up for teachers, you might not want to bombard your team with emails about new calendar events being created for them.
To remove the email notification of a new calendar being added to their account your will need to append your endPoint variable with,
?sendNotifications=false
.
Your endpoint line should now look like this:
1 |
const endPoint = `https://www.googleapis.com/calendar/v3/calendars/${calId}/acl?sendNotifications=false`; |
addCalendarToUserList(user, calendar)
The addCalendarToUserList(user, calendar)
function first assumes the user’s account before accessing their calendar list accepting the new calendar and displaying it in their list.
The function takes two arguments:
user
: the user who received the new calendar subscription request.calendar
: the calendar id (email).
Note: I’ve already covered a lot of the same workflow in the shareCalendar()
function. So I will only cover the differences below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
/** * Add the calendar to the the users calendar list and * select the calendar. * your calendar with the user. * @param{string} calId - The calendar ID to be shared. * @param{string} user - the user's email. * @returns{Object} Containing details of the added calendar. */ function addCalendarToUserList(user, calendar) { let service = getOAuthService(user); service.reset(); if (service.hasAccess()) { const content = JSON.stringify({ 'id':calendar, 'hidden':false, 'selected': true }); const endPoint = 'https://www.googleapis.com/calendar/v3/users/me/calendarList'; const response = UrlFetchApp.fetch(endPoint, { method:'POST', headers: { "Content-type": "application/json", "Authorization": 'Bearer ' + service.getAccessToken(), }, payload: content }); console.log(response.getContentText()); return response.getContentText(); }; }; |
As you can see, setting up the OAuth service is virtually the same. In this function, however, we set the argument for getOAuthService(user)
to the user so we can work on their behalf.
The Google Calendar API – Calendar List
This time around we need to update the user’s calendar list. That is the list of calendars you can find on the bottom right sidebar that you can check or uncheck to display.
All headers and the method of this HTTP request are the same as the shareCalendar()
function.
For our content this time we need to provide the shared calendar id (Line 16). Any new unaccepted calendar subscription request is automatically set to ‘hidden’ from the list (Line 17). We need to set this hidden then to false and to ensure it is displaying on the user’s list of calendars set selected to true (Line 18). This is the same as checking the box beside the calendar.
The returned JSON in the response variable should look a little like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
{ "kind": "calendar#calendarListEntry", "etag": "\"1642956776377220\"", "id": "e_vhnj1arsvt7t1vve2klu28n5kg@group.calendar.google.com", "summary": "Test Calendar", "timeZone": "UTC", "colorId": "5", "backgroundColor": "#ff7537", "foregroundColor": "#000000", "selected": true, "accessRole": "reader", "defaultReminders": [], "conferenceProperties": { "allowedConferenceSolutionTypes": [ "hangoutsMeet" ] } } |
Conclusion
As you can see this is not a clean-cut process and involves several steps to:
- Create a Google Apps Script Project.
- Create or use an existing Google Cloud project.
- Add the OAuth library.
- Create a Service Account.
- Add the service account JSON to your Apps Script Project.
- Apply Domain-Wide Delegation of Authority to your service account project.
- And finally, write your script.
It really makes you feel for the developers who regularly develop in other languages outside of Google Apps Script.
If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.
Other Service Account examples
I found it takes a few goes in different scenarios to feel confident in using service accounts. Below I have provided a list of other excellent tutorials and references on the topic that well work a run-through:
- The GitHub samples from the Apps Script Oauth2 library repo.
- Dimitry’s awesome 3 example set: How to Use Service Accounts and OAuth2 in Google Apps Script
- Bruce Mcpherson’s excellent: Using a Service Account Tutorial.
- Stéphane’s: Use a Google Sheets as a database in Apps Script without sharing it
- Doc Tanaike’s: Retrieving Access Token for Service Account using Google Apps Script
- Jeffrey Daube: How to use GCP service accounts with Google Apps Script projects to automate actions in G Suite
- Smart Recruiter’s setup process for creating a Service Account and Domain Wide Delegation of Authority
If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.
~Yagi
Changelog
- 15 Aug 2022 – Added chapter, “Bonus! Remove Notification email for user”. Special thanks to Nick M for raising this one.
Hi there, found this very helpful, thanks.
I’d like to be able to subscribe more than 1 calendar, could you point me in the right direction for amending your code please? I’ve played around with ‘for each’ and arrays, but don’t seem to be getting anywhere!
My first time playing around with Google Script.
Thanks in advance.
Simon