Last active
January 18, 2021 01:13
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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