How to Write Emails on Google Sheets via the app Scritp?

How to Write Emails on Google Sheets via the app Scritp?

We write the function in the Google App script to fetch the emails and store them in a Google sheet.

First, we create a new sheet called Email Threads and In the sheet, we will fetch the Thread ID, Subject, and Message Count.

In the function, first, we get the active sheet and also get the sheet by name called Email Threads using getSheetByName(). getSheetByName Method Returns a sheet with the given name. After that, we will get all Inbox Threads using the getInboxThreads Method.

We get the subject using the getFirstMessageSubject Method, we get the Thread ID using the getId Method, and the Message Count using the getMessageCount method. Created the one-dimensional array with three elements and then pushed the one-dimensional array into the final array.

Below are the function code.

function stored_emails_in_google_sheet(){
  var sh = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = sh.getSheetByName('Email Threads');
  var all_threads = GmailApp.getInboxThreads();
  var final_array = [];
   for(var cd=0; cd<all_threads.length; cd++)
   {
        var sub_threads = all_threads[cd];
        var subject = sub_threads.getFirstMessageSubject();
        var threadID = sub_threads.getId();
        var message_count = sub_threads.getMessageCount();
        var labels = sub_threads.getLabels();
        var temp = [threadID,subject,message_count,labels];
        final_array.push(temp); 
   }

   if(final_array.length>0)
   {
    var nextRow = sheet.getLastRow()+1;
    sheet.getRange(nextRow,1,final_array.length, final_array[0].length).setValues(final_array);

   }
}
Techinfo Avatar

Leave a Reply

Your email address will not be published. Required fields are marked *