adding a condition to import only new emails

261 views
Skip to first unread message

Hussein Osseily

unread,
Dec 8, 2022, 7:48:56 AM12/8/22
to Google Apps Script Community
Hello Everyone, 

I have an inbox (gmail) where i receive electronic emails from 1 user email, its only dedicated for this. So I could find a ready made script on the web to import emails from gmail into sheets, but what it does is that every time i hit import emails , it imports all the email in inbox even if its already there. 

Is there a way to add a condition to this script below inorder to make it import only the emails that were not imported during the last time i pressed the "import emails" 

and if its possible to have the  var dateTime display the time as well date + hh:mm:ss

Just to mention that i have a very low knowledge in google apps script

Thanks in advance 

Here is the script: 

function getGmailEmails(){
var threads = GmailApp.getInboxThreads();
for(var i = 0; i < threads.length; i++){
     var messages = threads[i].getMessages();
     var msgCount = threads[i].getMessageCount();
   for (var j = 0; j <messages.length; j++){
      message = messages[j];
      if (message.isInInbox()){
        extractDetails(message,msgCount);
       }
    }
   }
}
function extractDetails(message, msgCount){
   var spreadSheetId='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx;
   var sheetname = "SITA";
   var ss = SpreadsheetApp.openById(spreadSheetId);
   var timezone = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone();
   var sheet = ss.getSheetByName(sheetname);
   const today = new Date();
var dateTime = Utilities.formatDate(message.getDate(), timezone, "dd-MM-yyyy");
        var subjectText = message.getSubject();
        var fromSend = message.getFrom();
        var toSend = message.getTo();
        var bodyContent = message.getPlainBody();
       sheet.appendRow([dateTime, msgCount, fromSend, toSend,   subjectText, bodyContent]);
}
function onOpen(e) {
SpreadsheetApp.getUi()
.createMenu('Click to Fetch SITA Messages')
.addItem('Get Email', 'getGmailEmails')
.addToUi();
}
 


cwl...@gmail.com

unread,
Dec 12, 2022, 10:17:06 AM12/12/22
to Google Apps Script Community
Instead of using  " GmailApp.getInboxThreads();" , try playing around with a filter or query like in the search box at the top of your gmail:

var filter = "in:inbox is:unread from:someone...@example.com"
var threads = GmailApp.search(filter);
Reply all
Reply to author
Forward
0 new messages