12
votes

I'm wondering if it would be possible to create an apps script that monitors my inbox or a certain label in gmail, and when an email is received, import it to a google spreadsheet

The simpler of the two would be to import all emails that are caught in a certain label, which is easily done using filters in gmail itself, so I'd assume this would be the easier option

If it's possible, could someone link me to an apps script that already does this or point me in the right direction to get started? I've got some, albeit minimal experience with apps script so go easy on me :)

2

2 Answers

12
votes

Here is a small code to start with, I did limit the request to the first 10 threads to make it short and used a label that I had ... don't forget to change its name before you test it ;-)

    function getMessagesWithLabel() {
     var destArray = new Array();
      var threads = GmailApp.getUserLabelByName('Facebook').getThreads(1,10);

      for(var n in threads){
            var msg = threads[n].getMessages();
            var destArrayRow = new Array();
            destArrayRow.push('thread has '+threads[n].getMessageCount()+' messages');
              for(var m in msg){
                         destArrayRow.push(msg[m].getSubject());
               }
      destArray.push(destArrayRow);           
            }
    Logger.log(destArray);
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sh = ss.getActiveSheet();
    if(ss.getLastRow()==0){sh.getRange(1,1).setValue('getMessagesWithLabel() RESULTS')};
    sh.getRange(ss.getLastRow()+1,1,destArray.length,destArray[0].length).setValues(destArray)
    }
3
votes

Yes, it is possible to write a script to do what you've outlined. See the GmailApp documentation of Apps Script for methods that you can use to do so.