0

I'm trying to pull data from gmail (ie. from, to, date, subject, body, etc.) but I'm getting an error saying the getBody() length is too long:

your input contains more than the maximum of 50000 characters in a single cell

I'm trying to have a cut off of characters or just not pull the email with a Body over the character limit. Also, I'm pretty out of practice on this and it's not working...

//Allow user to select label(s) and date range
function getGmailEmails() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var label = sheet.getRange(1, 3).getValue();
  var after = sheet.getRange(2, 3).getDisplayValue();
  var before = sheet.getRange(3, 3).getDisplayValue();
  var threads = GmailApp.search("label:" + label + " AND " + "after:" + after + " AND " + "before:" + before);

  // Export emails into table of values in google sheet
  // Character length cutoff is 2000, the cell with get Body would tell you to go to the inbox
  var values = [];
  for (var i = 0; i < threads.length < 2000; i++) {
    var temp = [];
    var label = threads[i].getLabels().map(e => e.getName()).join(", ");
    let messages = threads[i].getMessages();
    for (var j = 0; j < messages.length; j++) {
      temp.push([
        label,
        messages[j].getFrom(),
        messages[j].getTo(),
        messages[j].getCc(),
        messages[j].getDate(),
        messages[j].getSubject(),
        messages[j].getBody(),
        messages[0].getId()
      ]);
    }
    values = values.concat(temp);
  }
  sheet.getRange(6, 1, values.length, values[0].length).setValues(values);
}
Rubén
  • 34,714
  • 9
  • 70
  • 166

1 Answers1

1

One way is by using String.prototype.slice().

Replace

messages[j].getBody(),

by

messages[j].getBody().slice(0,50000),

Related

Rubén
  • 34,714
  • 9
  • 70
  • 166
  • is there any difference between using substring or slice for this? just curious. – Allister Lobo Feb 05 '22 at 19:01
  • @AllisterLobo See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice – Rubén Feb 05 '22 at 19:21