0
votes

I am trying to create a script that will count the number of emails with a certain label every day. I have the following code currently set up;

function CountVoicemail()  
{
var Label = GmailApp.getUserLabelByName("X140");
var LabelName = Label.getName();
var date = new Date();
var NextDate = date+1; 
var Mails = GmailApp.search('label:"+LabelName+" after:"+date+" 
before:"+NextDate+"',0, 500);              
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data 
Sheet");
sheet.appendRow([LabelName, date,Mails.length]);
}

Right now I have the code to write its results to a Sheet as a new row with the first column being the label name, the second column being the date, and the third column the number of emails in that label for the particular date the code is being run (going to have a daily trigger). However, right now the code is just returning a value of zero for the number of emails (the # is not zero). I think this is due to how I'm trying to count the emails (variable "Mails" which uses the GmailApp.Search call) and that I am using variables inside my search call. What can I do make this work? Or is something else causing the issue?

1

1 Answers

0
votes

I'm not sure but perhaps you meant something like this?

function CountVoicemail() {
  var Label = GmailApp.getUserLabelByName("X140");
  var name = Label.getName();
  var start=new Date(new Date().getFullYear(),new Date().getMonth(),new Date().getDate());
  var end=new Date(new Date().getFullYear(),new Date().getMonth(),new Date().getDate()+1);
  var Mails = GmailApp.search(Utilities.formatString('label:%s after:%s before: %s',name,start,end));
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data Sheet");
  sheet.appendRow([LabelName, date,Mails.length]);
}

Here's the change to reformat the dates:

function CountVoicemail() {
  var Label = GmailApp.getUserLabelByName("X140");
  var name = Label.getName();
  var start=new Date(new Date().getFullYear(),new Date().getMonth(),new Date().getDate());
  var end=new Date(new Date().getFullYear(),new Date().getMonth(),new Date().getDate()+1);
  var Mails = GmailApp.search(Utilities.formatString('label:%s after:%s before: %s',name,Utilities.formatDate(start, Session.getScriptTimeZone(), "yyyy/MM/dd"),Utilities.formatDate(end, Session.getScriptTimeZone(), "yyyy/MM/dd")));
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data Sheet");
  sheet.appendRow([LabelName, date,Mails.length]);
}