Below is the code that I wrote and tested that perfectly performs steps 2, 3, and 4 you described.
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 errors in your code was that the appendRow function takes an array of elements specified in brackets [ ] .
Depending on where you are attaching this script, your line of code:
var ss = SpreadsheetApp.openById(id);
not required if the script is written in the table script editor where you want these emails to be registered. However, if there are multiple sheets in this table, you can replace my row
var ss = SpreadsheetApp.getActiveSheet();
by
var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheetByName("Sheet1");
Another suggestion is that the current code will provide you with HTML messages. Therefore, if you want to receive the message in plain text, as you see, use:
var msg = messages[i].getPlainBody();
Now you can write another function for the regular expression and pass the msg message to this. Hope this helps!
source share