Save Gmail Messages as PDF - Google Apps Script

S
Published in: Gmail - 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<threads.length; t++) {

      threads[t].removeLabel(label);
      var msgs = threads[t].getMessages();

      var html = "";
      var attachments = [];

      var subject = threads[t].getFirstMessageSubject();

      /* Append all the threads in a message in an HTML document */
      for (var m=0; m<msgs.length; m++) {

        var msg = msgs[m];

        html += "From: " + msg.getFrom() + "<br />";
        html += "To: " + msg.getTo() + "<br />";
        html += "Date: " + msg.getDate() + "<br />";
        html += "Subject: " + msg.getSubject() + "<br />";
        html += "<hr />";
        html += msg.getBody().replace(/<img[^>]*>/g,"");
        html += "<hr />";

        var atts = msg.getAttachments();
        for (var a=0; a<atts.length; a++) {
          attachments.push(atts[a]);
        }
      }

      /* Save the attachment files and create links in the document's footer */
      if (attachments.length > 0) {
        var footer = "<strong>Attachments:</strong><ul>";
        for (var z=0; z<attachments.length; z++) {
          var file = folder.createFile(attachments[z]);
          footer += "<li><a href='" + file.getUrl() + "'>" + file.getName() + "</a></li>";
        }
        html += footer + "</ul>";
      }

      /* 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);

    }
  }
}
📮  Subscribe to our Email Newsletter for Google tips and tutorials!
Published in: Gmail - Google Apps Script

Looking for something? Find here!

Meet the Author

Web Geek, Google Developer Expert
A
Amit Agarwal

Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India. He is the developer of Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

Get in touch

Google Add-ons

Do more with your Gmail and GSuite account
G

We build bespoke solutions that use the capabilities and the features of Google Workspace for automating business processes and driving work productivity.

  1. Mail Merge with Attachments
    Send personalized email to your Google Contact with a Google Sheet and Gmail
  2. Save Emails and Attachments
    Download email messages and file attachments from Gmail to your Google Drive
  3. Google Forms Email Notifications
    Send email notifications to multiple people when a new Google Form is submitted
  4. Document Studio
    Create beautiful pixel perfect documents merging data from Google Sheets and Google Forms
  5. Creator Studio for Google Slides
    Turn your Google Slides presentations into animated GIFs and videos for uploading to YouTube