Search code examples
google-apps-scriptgmail

Gmail App: Find threads which have a calendar entry


Some messages have calendar entries at the top of them like this: enter image description here

In GScript, is there any way to find messages which have these calendar entries? If so, how does one extract the information from it?

Update

I took a lucky shot and found that it's classed as an attachment (of type ics), but there still remains the issue of extracting the data from this file...


Solution

  • Try this:

    function getIcs(){
      var threads = GmailApp.getInboxThreads();
      var thread, messages, message, attachments, attachment;
      var result = [];
    
      for (var i = 0; i < threads.length; i++){
        messages = threads[i].getMessages();
        for (var j = 0; j < messages.length; j++){
          message = messages[j];
          attachments = message.getAttachments();
          for (var k = 0; k < attachments.length; k++){
            attachment = attachments[k];        
            if(attachment){
              if (attachment.getContentType() == "application/ics"){
                Logger.log("found ics");//continue;
                result.push(message);
              }
            }
          }
        }
      }
      return result;
    }
    

    This method will view every thread, every message in it and every attachment in each message, and returns a list of the message objects that have an attachment of type application/ics.

    UPDATE

    In addition to my previous code, the following function will return an array of event objects based on the attachments found in the other method:

    function getSutff(){
      var msgs = getIcs();
      var ics;
      var position;
      var eventId;
      var event = [];
    
      for (var i = 0; i < msgs.length; i++){
        ics = msgs[i].getAttachments()[0].getDataAsString();
        position = (ics.search("UID:")) + 4;
        eventId = ics.substr(position,26);
        event.push(CalendarApp.getEventById(eventId));
      }
      Logger.log(event)
      return event;
    }