Copying text from email and pasting in Google Doc using Google Script App

40 Views Asked by At

I spent about 3 days looking at this. What I intend to do is collect emails that are sent to me and paste them at the top of a Google Doc, sort of like a running archive.

So the first phase of me trying to do this is complete. I was able to get text from an email and put it in google docs. The next part is trying to keep the format of the text AND placing a page break after the text. The below function allows me to get text from an email (I found a way to get HTML for email as well but can't seem to paste it correctly in the Google Doc)

function getEmailBody() {
  var message
  var searchedEmailThreads = GmailApp.search('label:announcement')
  
  ... code to search emails, returning searchEmailThreads array ...

  message = searchedEmailThreads[0].getMessages()[0]
  var oldBodyHTML = message.getPlainBody();
  // var oldBodyHTML = message.getBody() - gets html format but how can I paste it in the doc?

  return oldBodyHTML
}

The below function is to write it to the Google Doc. I know it is inserttext but I haven't found a way to insert as formatted text.

function writeToDocument(htmlBody) {
   var document = DocumentApp.openById({document_ID})

  document.getBody().editAsText().insertText(0, htmlBody)
  // document.appendParagraph("A paragraph.")
  // document.appendPageBreak()
}

My questions are:

  1. How can I paste into Google Doc as formatted text? Do I need to save the getBody() in an HTML file?
  2. How can I apply a page break at the end of the text mentioned that I just copied from the email?

Please and thank you ahead of time for any help that you can give!

0

There are 0 best solutions below