Running a Startup on AWS? Get Funding With AWS JumpStart. Click Here to Learn More

2021 Fillmore Street #1128

}

24/7 solutions

Top 10 Cloud Providers

How to Save Emails to Google Drive as PDF Files

Travor House A self-motivated digital marketing specialist with 3+ years of experience advertising in the financial services industry. While I wear several marketing hats, my primary focus is on content strategy and curation. I aim to consistently challenge myself and position my skills toward personal and professional endeavors that lead to measurable results. LinkedIn
Today, I needed to save some of my Gmail emails to Google Drive as PDF files. I looked around for a bit. I tried CloudHQ, but I didn’t want to pay. Next, I looked into exporting my Google Data into an MBOX type format. This seemed reasonable at first, but then I had to find a tool to import MBOX into. I chose Thunderbird, but then Thunderbird wanted me to pay. Next, I tried a couple of other Chrome Extensions. Neither of these worked well. Finally, I determined to get the emails to be outputted in the format that I wanted without paying, it was probably best to write a Google App Script. What’s a Google App Script? Well, according to Google, “Apps Script is a scripting platform developed by Google for light-weight application development in the G Suite platform.” You can learn more here. If you have a Gmail account, it looks like you should be able to use it. I started by assigning all of the emails in Gmail that I wanted to export a Label. For the purpose of this tutorial, I created the label “Export”   After I created the label “Export”, I next associated the label with the emails that I wanted to save as PDF. After selecting the emails that I wanted to export. I logged into the Google App Scripts by typing this url, http://script.google.com/. Once in Google App Scripts, I created a new project entitled Save Gmail to Google Drive. I had to give Google App Scripts access to both my Gmail and Google Drive. Gmail to Google Drive App Script Project I double-clicked on the project and entered the following javascript code.
function saveGmailToGoogleDriveAsPDF() {
  var gmailLabels  = "Export ";
  var driveFolder  = "My Gmail";
  //Search Gmail for our Export Label
  //GMail will return the threads of the email conversations. This is different than the raw emails. This is all of the emails within a thread.
  var threads = GmailApp.search("label:" + gmailLabels, 0, 3);
  if (threads.length > 0) {
   /*GetFolders returns a FolderIterator. See if we have any folders. If not, then create one.
    var folders = DriveApp.getFoldersByName(driveFolder);
    var folder;
    if ( folders.hasNext() ) {
        folder = folders.next();
    }
    else
        folder = DriveApp.createFolder(driveFolder);
    /*Iterate through the threads of emails*/
    for (var t=0; t<threads.length; t++) {
      var msgs = threads[t].getMessages();
      var html = "";
      var attachments = [];
      //Get the Subject of the first email in the thread. We'll use the Subject in the name of the email
      var subject = threads[t].getFirstMessageSubject();
      /* We're going to stick all of the messages in this thread into one pdf  */
      for (var m=0; m<msgs.length; m++) {
        //designate what the first date is in the thread, we'll use this in the name as well
        var firstDate;
        var msg = msgs[m];
        var date;
        if ( m == 0 )
        {
          firstDate = msg.getDate();
          date = firstDate;
        }
        else
          date = msg.getDate()
        //Build the HTML, you may wany to introduce some hrs. The wordpress pre tag was behaving oddly with html tags.
        html += "From: " + msg.getFrom() + "";
        html += "To: " + msg.getTo() + "";
        html += "Date: " + date  + "";
        html += "Subject: " + msg.getSubject() + "";
        html += msg.getBody().replace(/<img[^>]*>/g,"");
        //Snag the attachments so we can save them for later
        var atts = msg.getAttachments();
        for (var a=0; a<atts.length; a++) {
          attachments.push(atts[a]);
        }
      }
      /* Iterate through the attachment files and create links in the pdf's footer */
      if (attachments.length > 0) {
        var footer = "Attachments:";
        for (var z=0; z<attachments.length; z++) {
          var attachment = attachments[z]
          var filename = attachment.getName();
          //You may want to treat different ContentType's differently...
          var contentType = attachment.getContentType();
          var iter = folder.getFilesByName( filename  );
          var file;
          if ( iter.hasNext() )
            file = iter.next()
          else
            file = folder.createFile(attachment);
          footer += "" + file.getName() + "";
        }
        html += footer";
      }
      //Format the name to differentiate between Emails and attachments. Otherwise, everything starts to look the same.
      //Write the formatted firstDate into the name
      var filename = "Email: " + getFormattedDate( firstDate ) +": "+ subject;
      var tempFile = DriveApp.createFile(filename+".html", html, "text/html");
      /* Convert the Email Thread into a PDF File */
      folder.createFile(tempFile.getAs("application/pdf")).setName(filename + ".pdf");
      /*Get rid of the tmp file*/
      tempFile.setTrashed(true);
    }
  }
}
Now to format the date use the following bit of code
function getFormattedDate(  date )
{
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var min = date.getMinutes();
    var sec = date.getSeconds();
    month = (month < 10 ? "0" : "") + month;
    day = (day < 10 ? "0" : "") + day;
    hour = (hour < 10 ? "0" : "") + hour;
    min = (min < 10 ? "0" : "") + min;
    sec = (sec < 10 ? "0" : "") + sec;
    var str = date.getFullYear() + "-" + month + "-" + day + "_" +  hour + ":" + min + " ";
    /*alert(str);*/
    return str;
}
Next, run the code in Google App Scripts by hitting the play button.
Execute Google App Script Project to save Gmails to Google Drive as PDF

Execute Google App Script Project to save Gmails to Google Drive as PDF

  Navigate to your Google Drive My Gmail Folder. Voila! You’ll see your pdfs. This code will also handle attachments, which include calendar event types. Ping me if you have any issues, and I can share the script with you.  
Export Emails to Google Drive as PDF

Export Emails to Google Drive as PDF

Travor House
Travor House

A self-motivated digital marketing specialist with 3+ years of experience advertising in the financial services industry.

While I wear several marketing hats, my primary focus is on content strategy and curation.

I aim to consistently challenge myself and position my skills toward personal and professional endeavors that lead to measurable results.

Related Articles

Here’s Why You Should Work with an AWS Partner

Here’s Why You Should Work with an AWS Partner

Amazon Web Services is understandably a difficult platform to adapt to and utilize fully upon first getting started. Some organizations can be selected to become certified partners to indirectly extend services to help build on the Amazon Cloud. Finding a certified company to help build out is undoubtedly the best way to significantly simplify, streamline, and reduce the cost of utilizing AWS.

Amazon Web Services – CodeCatalyst

Amazon Web Services – CodeCatalyst

When a development team is building out an application, it helps to have access to the same resources, have the tools for planning and testing, and to have access to the application all in one place. CodeCatalyst comes with a slew of continuous integration/continuous development (CI/CD) tools and can leverage other AWS services and be connected to other AWS projects on an account. As a collaborative tool, it is easy to introduce new members into the project and to log all activity or all tests from a single dashboard. It’s a complete package of all the tools needed to securely work on every step of an application’s lifecycle.

The Definitive Guide to AWS Pricing

The Definitive Guide to AWS Pricing

Perhaps the biggest issue with AWS that its competitors edge out on is the confusing pricing model. It does promise the capacity to help users save significantly on funds that otherwise by avoiding spending on unnecessary resources, but getting to that point isn’t always clear. We will be covering in greater detail how this works.

Download our 10-Step Cloud Migration ChecklistYou'll get direct access to our full-length guide on Google Docs. From here, you will be able to make a copy, download the content, and share it with your team.