A
A
Aleksandr2018-06-11 11:15:40
Google Apps Script
Aleksandr, 2018-06-11 11:15:40

Why doesn't the script select letters by the given label (but removes the label from the letters correctly)?

I dug up a script for copying letters from Gmail to a Google spreadsheet. Corrected to work not only with the active book (table), but also with the closed one.
Problem: Emails from the last three days are saved, not those for which the label is specified. (The label is removed from the letter correctly.)

The code
var SHEET_ID = "SPREADSHEET_ID_HERE"; 
var SHEET_NAME = "Sheet1";
var EMAIL_LABEL = "__renew";

function saveEmails() {

  var ss = SpreadsheetApp.openById(SHEET_ID);
  var sheet = ss.getSheetByName(SHEET_NAME);

  var label = GmailApp.getUserLabelByName(EMAIL_LABEL);
  var threads = label.getThreads();

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

    for (var j=0; j<messages.length; j++)
    {
      var dat = messages[j].getDate();
      var msg = messages[j].getBody();

      ss.appendRow(["", dat, "", msg])
    }
      threads[i].removeLabel(label); //убирает ярлык с письма
  }
}


PS What code is needed so that all the labels assigned to the letter are also entered in the table?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Samokhin, 2018-06-12
@hda1

And if you try to search for letters like this:

var EMAIL_LABEL = '__renew';
var query = 'in:inbox label:' + EMAIL_LABEL;
var threads = GmailApp.search(query);
var messages = GmailApp.getMessagesForThreads(threads);
for (var i = 0; i < messages.length; i++) {
  for (var j = 0; j < messages[i].length; j++) {
    Logger.log(messages[i][j].getDate() + ' ' + messages[i][j].getSubject());
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question