Home > front end >  How to get daily number of emails under a label in gmail to google sheets?
How to get daily number of emails under a label in gmail to google sheets?

Time:12-16

Editing my question as requested.

I need to get the daily number of emails under a label in gmail to google sheets, in a way that I get the date and the number of emails per day (not including answers on the thread, just the first email received to be counted).

Sample:

example

Not my code, credit to @Suyash Gandhi

I tried using Suyash's code:

function CountEmail() {
var label = GmailApp.getUserLabelByName("LabelName");
var labelname = label.getName();
var mails = label.getThreads();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var date = new Date();
sheet.appendRow([labelname,date,mails.length]);
}

But it gives me the error "TypeError: Cannot read properties of null (reading 'getName') CountEmail @ CountEmail.gs:4"

How can I make it work?

I am very new to this and don't fully understand how scripts can be edited, appreciate any help.

CodePudding user response:

Provides Date,Count,list of subjects and sorts the output list by date and displays in on a sheet

function CountEmail() {
  const ts = GmailApp.search("label: ");//update label
  let obj = {pA:[]}
  ts.forEach(t => { 
    let s = t.getFirstMessageSubject();
    let dt = t.getMessages()[0].getDate();
    let p = `${dt.getFullYear()}~${dt.getMonth()}~${dt.getDate()}`
    if(!obj.hasOwnProperty(p)) {
      obj[p] = {date:p,subject:[s],count:1};
      obj.pA.push(p);
    } else {
      obj[p].subject.push(s);
      obj[p].count = Number(obj[p].count)   1;
    }
  });
  let o = obj.pA.map(p => {
    return [obj[p].date,obj[p].count,obj[p].subject.join('\n')];
  });
  o.sort((a,b) => {
    let ta = a[0].split('~');
    let tb = b[0].split('~');
    let va = new Date(ta[0],ta[1],ta[2]);
    let vb = new Date(tb[0],tb[1],tb[2]);
    return va - vb;
  })
  o.unshift(['Date','Count','Subjects'])
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet0');//update sheet
  sh.clearContents();
  sh.getRange(1,1,o.length,o[0].length).setValues(o);
}
  • Related