Search code examples
google-apps-scriptgoogle-sheetsgmail

Extract the exact subjects and update the google sheets using apps script


I have found a below mentioned apps script to get the subject name of the emails from the particular label and update the google sheets.

function getSubjects() {
var sheet = SpreadsheetApp.getActiveSheet();
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();

var label = GmailApp.getUserLabelByName("Test");
var threads = label.getThreads();
var row = 2;

for (var i = 0; i < threads.length; i++) {
var messages=threads[i].getMessages();

for (var m=0; m < messages.length; m++) {  
sheet.getRange(row,1).setValue(messages[m].getSubject());
row++;
  }
 }
};

On daily basis, I will receive more than 100 emails with the same subject lines with small modifications. So, I need to get in the google sheets only the emails that have a subject line which includes the word "Pending".

I am hoping someone can help me make this example work.


Solution

  • Never-mind. I have figured it out. Below is the updated code which is working as expected.

    function getSubject() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
      var threads = GmailApp.search('subject: Successfully Completed is:Test/2019_08');
      var row = 2;
      for (var i = 0; i < threads.length; i++) {
      var messages=threads[i].getMessages();
      for (var m=0; m < messages.length; m++) {  
      sheet.getRange(row,1).setValue(messages[m].getSubject());
      row++;
          }
       }
    };