Apps Script to save Gmail Messages as PDF in Drive

Here, you will understand to create a PDF file from your gmail message, this Google Apps Script reads the HTML body of Inbox threads, remove any inline images, saves the thread as an HTML file and then converts the HTML into a PDF. Temporary file is moved to trash after conversion to PDF. This one is probably the simplest of all, a more improved version is also written by Amit Agarwal https://ctrlq.org/code/19117-save-gmail-as-pdf



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function doGet() {
  var firstThread = GmailApp.getInboxThreads(0,1)[0];
  var message = firstThread.getMessages()[0];
  var attach = message.getAttachments();
  var body = message.getBody();//is a string
  var htmlfile = DriveApp.createFile('body.html', body, "text/html");
  var bodydocpdf = htmlfile.getAs('application/pdf').getBytes();
  DriveApp.createFile(htmlfile.getAs('application/pdf'));
  htmlfile.setTrashed(true);
  return ContentService.createTextOutput("Done - Check your drive");
}

Comments