Skip to content

Instantly share code, notes, and snippets.

@zaskem

zaskem/ExportEmailToPDF.gs

Last active Jan 18, 2021
Embed
What would you like to do?
A basic Google Apps Script that, when triggered from a Google Sheet, will export Gmail messages by label to PDF in the drive folder specified and log the basic information to she calling spreadsheet.
function exportEmailToPDF() {
// Script Variables to Set
  var drivePath = DriveApp.getFolderById("LongStringOfTheDestinationFolderIdentifier");
  var plaintextPath = DriveApp.getFolderById("LongStringOfTheIntermediateFolderIdentifier");
  var label = GmailApp.getUserLabelByName("YourLabelNameGoesHere");
// End of Script Variables to Set
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  //Logger.log(label.getName()); // Write to log the name of the label (can help identify label typos)
  var threads = label.getThreads();
  for (var i=0; i<threads.length; i++)
  {
    var messages = threads[i].getMessages();
    for (var j=0; j<messages.length; j++)
    {
// Grab the message
      var html = messages[j].getBody();
      var subject = messages[j].getSubject();
      var date = Utilities.formatDate(messages[j].getDate(), 'America/Chicago', 'MM-dd-yyyy');
//Logger.log(subject+'-'+date); // Write to log the subject and date of the message (troubleshooting)
// Write the intermediary message to file
      var textFile = plaintextPath.createFile(label.getName()+'-'+subject+'-'+date, html,"text/html");
// Convert to PDF and save
      var pdfBlob = textFile.getAs(MimeType.PDF);
      var pdf = drivePath.createFile(pdfBlob);
      var pdfLink = pdf.getUrl();
      // Write the basics to our parent spreadsheet
      sheet.appendRow([date,subject,pdfLink])
// Remove the intermediary file
plaintextPath.removeFile(textFile);
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment