Removing html formatting when fetching gmail message body in javascript

I would like to remove html formatting in my google script apps. I am currently searching for email and printing the results to a google spreadsheet. I would like to know if there is a way to replace the text. I know about regex, but I don't think it works with the getBody function.

I would really appreciate some feedback or some help on this.

Code:

function Search() {

var sheet   = SpreadsheetApp.getActiveSheet();
var row     = 2;

// Clear existing search results
sheet.getRange(2, 1, sheet.getMaxRows() - 1, 4).clearContent();

// Which Gmail Label should be searched?
var label   = sheet.getRange("F3").getValue();

// Get the Regular Expression Search Pattern
var pattern = sheet.getRange("F4").getValue();

// Retrieve all threads of the specified label
var threads = GmailApp.search("in:" + label);

for (var i = 0; i < threads.length; i++) {

var messages = threads[i].getMessages();

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

// Does the message content match the search pattern?
if (msg.search(pattern) !== -1) {


 // Print the message subject
 sheet.getRange(row,3).setValue(messages[m].getBody());

      

+3


source to share


2 answers


Replace this:

// Print the message subject
sheet.getRange(row,3).setValue(messages[m].getBody());

      

Wherein:



// Print the message subject
sheet.getRange(row,3).setValue(getTextFromHtml(messages[m].getBody()));

      

The feature getTextFromHtml()

was adapted from this answer , adding handling for some basic formatting (numbered and bullet lists, paragraph breaks).

function getTextFromHtml(html) {
  return getTextFromNode(Xml.parse(html, true).getElement());
}

var _itemNum; // Used to lead unordered & ordered list items.

function getTextFromNode(x) {
  switch(x.toString()) {
    case 'XmlText': return x.toXmlString();
    case 'XmlElement':
      var name = x.getName().getLocalName();
      Logger.log(name);
      var pre = '';
      var post = '';
      switch (name) {
        case 'br':
        case 'p':
          pre = '';
          post = '\n';
          break;
        case 'ul':
          pre = '';
          post = '\n';
          itemNum = 0;
          break;
        case 'ol':
          pre = '';
          post = '\n';
          _itemNum = 1;
          break;
        case 'li':
          pre = '\n' + (_itemNum == 0 ? ' - ' : (' '+ _itemNum++ +'. '));
          post = '';
          break;
        default:
          pre = '';
          post = '';
          break;
      }
      return pre + x.getNodes().map(getTextFromNode).join('') + post;
    default: return '';
  }
}

      

+3


source


From this answer: Google Apps Scripting - Extracting data from gmail into a spreadsheet



You can drop the getTextFromHTML function entirely by simply using getPlainBody (); instead of getBody () ;.

+1


source







All Articles