Categories
Code

Save Gmail Messages as PDF – Google Apps Script

The Save Gmail to Google Drive program using Google Scripts to save Gmail message as PDF using the built-in PDF converter of Google Docs (now Google Drive).

The Google Apps Script reads the HTML body of the Gmail threads, strips the inline images, saves the thread as an HTML file and then converts the HTML into a PDF. If there are any file attachments in the email thread, they are saved as well. The downloads links of the attachments are appended to the PDF as well.

function saveGmailAsPDF() { 
  
  var gmailLabels  = "PDF";  
  var driveFolder  = "My Gmail";
  
  var threads = GmailApp.search("in:" + gmailLabels, 0, 5);  
  
  if (threads.length > 0) {
    
    /* Google Drive folder where the Files would be saved */
    var folders = DriveApp.getFoldersByName(driveFolder);
    var folder = folders.hasNext() ? 
        folders.next() : DriveApp.createFolder(driveFolder);
    
    /* Gmail Label that contains the queue */
    var label = GmailApp.getUserLabelByName(gmailLabels) ?     
        GmailApp.getUserLabelByName(gmailLabels) : GmailApp.createLabel(driveFolder);
    
    for (var t=0; t";  
        html += "To: " + msg.getTo() + "
"; html += "Date: " + msg.getDate() + "
"; html += "Subject: " + msg.getSubject() + "
"; html += "
"; html += msg.getBody().replace(/]*>/g,""); html += "
"; var atts = msg.getAttachments(); for (var a=0; a 0) { var footer = "Attachments:
    "; for (var z=0; z" + file.getName() + ""; } html += footer + "
"; } /* Conver the Email Thread into a PDF File */ var tempFile = DriveApp.createFile("temp.html", html, "text/html"); folder.createFile(tempFile.getAs("application/pdf")).setName(subject + ".pdf"); tempFile.setTrashed(true); } } }