Skip to content

Instantly share code, notes, and snippets.

@zaskem
Last active January 18, 2021 01:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaskem/45e7152473b1aa28a6728a709e583933 to your computer and use it in GitHub Desktop.
Save zaskem/45e7152473b1aa28a6728a709e583933 to your computer and use it in GitHub Desktop.
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