Google Apps Scripts - Extract data from gmail into a spreadsheet

假装没事ソ 提交于 2019-11-30 04:03:05

Following is the code I wrote and tested that performs the steps 2, 3 and 4 mentioned by you perfectly well.

function myFunction() {

  var ss = SpreadsheetApp.getActiveSheet();

  var label = GmailApp.getUserLabelByName("MyLabel");
  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 msg = messages[j].getBody();
      var sub = messages[j].getSubject();
      var dat = messages[j].getDate();

      ss.appendRow([msg, sub, dat])
    }
      threads[i].removeLabel(label);
  }
}

One of the faults in your code was that the appendRow function accepts an array of elements specified within [ ] brackets.

Depending on where you're attaching this script, your line of code:

var ss = SpreadsheetApp.openById(id);

is not necessary if the script is being written in the script editor of the Spreadsheet where you want these emails to be logged. However, if there are multiple sheets in that spreadsheet, you can replace my line

var ss = SpreadsheetApp.getActiveSheet();

by

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");

Another suggestion is that the current code will give you messages in HTML format. Hence, if you want to get the message in plain text as you see it, use:

var msg = messages[i].getPlainBody();

Now you can write another function for regex and pass the message msg to that. Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!