0

The script is unable to extract emails get body /get plain body. Can any one guide?

function getEmails() {
var ss = SpreadsheetApp.getActiveSpreadsheet();  
var labels = GmailApp.getUserLabels(), emptyLabels = [];
// itterate through the labels
for (var i=0; i<labels.length; i++) {
try {
// create sheets and clear content
var sh = ss.getSheetByName(labels[i].getName()) || 
ss.insertSheet(labels[i].getName(), ss.getSheets().length);
sh.clear();

// get all messages    
  var eMails = GmailApp.getMessagesForThreads(
    GmailApp.search("label:" + labels[i].getName()))
      .reduce(function(a, b) {return a.concat(b);})
      .map(function(eMails) {return eMails.getPlainBody()});

 for (var j=0; j<eMails.length; j++)    {
    var messages = threads[j].getMessages();
    for (var k=0; k<messages.length; k++)       {
    var text = messages[k].getPlainBody();
    var matches = /From:(.*?)<(.*?)>/gi.exec(text);
    if (matches) 
    Logger.log(matches[1] + " :: " + matches[2]);
        } }

// sort and filter for unique entries  
var aEmails = eMails.sort().filter(function(el,m,a)
{if(m==a.indexOf(el))return 1;return 0});  
// create 2D-array
var aUnique = new Array();  
for(var n in aEmails) {
aUnique.push([aEmails[n]]);
}

// add data to corresponding sheet
sh.getRange(1, 1, aUnique.length, 1).setValues(aUnique);
} catch (e) {
emptyLabels.push(labels[i].getName());
}
}
ss.toast("These sheets are empty: " + emptyLabels);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.