Remove html formatting when getting Body of a gmai

2019-04-11 21:25发布

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

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

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());

2条回答
地球回转人心会变
2楼-- · 2019-04-11 22:19

From this answer: Google Apps Scripts - Extract data from gmail into a spreadsheet

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

查看更多
▲ chillily
3楼-- · 2019-04-11 22:25

Replace this:

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

With this:

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

The getTextFromHtml() function has been adapted from this answer, with the addition of handling for some basic formatting (numbered & 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 '';
  }
}
查看更多
登录 后发表回答