0
votes

I'm using Gmail apps script to forward emails with a certain label ... But I'd like to edit the body of the message prior to forwarding.

function fwdFB(){


var label = GmailApp.getUserLabelByName('fb');
  var threads = label.getThreads();
  for(var m in threads){
    var messages = threads[m].getMessages();
    for(var y in messages){ messages[y].forward('[email protected]',{from:'[email protected]'}) }
    threads[m].moveToTrash();
  }
}

I'm unclear as to how to insert the getBody() method to edit the message. (Specifically, I want to delete a certain HTML chunk from the message. It's the same chunk in each message.)

1

1 Answers

0
votes

The options of forward(recipient, options) do not offer an endpoint to modify the message body. You'll have to do it instead manually, by sending a message after modifying the body as desired.

Sample:

function fwdFB(){
var label = GmailApp.getUserLabelByName('fb');
  var threads = label.getThreads();
  for(var m in threads){
    var messages = threads[m].getMessages();
    for(var y in messages){ 
     var oldBody = messages[y].getBody();
     var newBody = oldBody.substring(1, 10)+" PS: This is a modification."
     var oldSubject = messages[y].getSubject();
      var newSubject = "Fwd: "+ oldSubject; 
      GmailApp.sendEmail('[email protected]', newSubject, newBody, {from:'[email protected]'})
    }
    threads[m].moveToTrash();
  }
}

UPDATE

If it is important for you to preserve the message history, you need to perform additional steps to thread the message. @tehhowch provides a good example of how to do so.