google-apps-scriptgoogle-drive-apigoogle-calendar-api

Create an event with an attachment on Calendar via Google apps script


I couldn't find a way to add an attachment to my calendar event. I hope there should be a simple way like below snippet,

function createNewEvent()
{
 var file = DriveApp.getFileById('1eqaThzYmTbZzP-my file id-rXrBrWDW8DwMNeU');   //get file to be attached
 var title  = 'Apollo 11 Landing';
 var startTime = new Date('January 20, 2016 20:00:00 UTC');
 var endTime = new Date('January 20, 2016 21:00:00 UTC');
 var options = {description:'Sample description', location: 'The Moon', attachments:file}; //can we add attachments like this?

 var event = CalendarApp.getDefaultCalendar().createEvent(title, startTime, endTime, options);
}

Is this possible?


Solution

  • Yes, this is possible. First you must enable the Advanced Calendar Service. Then you can do something like this:

    function createNewEvent() {
      var calendarId = ''; //Calendar Id String
      var fileId = ''; // File Id String
      var start = new Date('January 20, 2016 20:00:00 UTC');
      var end = new Date('January 20, 2016 21:00:00 UTC');
      var eventObj = {
        summary: 'Apollo 11 Landing',
        location: 'The Moon',
        description: 'Sample description',
        start: {dateTime: start.toISOString()},
        end: {dateTime: end.toISOString()},
        attachments: [{
            'fileUrl': 'https://drive.google.com/open?id=' + fileId,
            'title': 'Moon Docs'
        }]
      };
      var resp = Calendar.Events.insert(eventObj, calendarId, {'supportsAttachments': true});
      Logger.log(resp); // Check out the response in the logs!
    }
    

    For more options, check out the Events documentation.