Are you getting the most out of your AWS investment? Get your free AWS Well-Architected Assessment.

2021 Fillmore Street #1128

}

24/7 solutions

saveemailaspdf

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

AWS Think Big with Small Business Program’s Competitive Edge

AWS Think Big with Small Business Program’s Competitive Edge

The Amazon Cloud can help alleviate most issues involving transitioning the cloud. Businesses of any scope can hope to build solutions that are scalable and adaptable to their industry of work. Smaller or minority-owned businesses may still struggle to stand out among bigger companies or make an AWS environment as efficient as possible with fewer funds to spend. To alleviate these burdens, Amazon has the Think Big With Small Business program available through their Public Sector partnership program.

AWS Think Big for Small Business, Data Analytics, and Business Intelligence

AWS Think Big for Small Business, Data Analytics, and Business Intelligence

The AWS Think Big for Small Business Program is an outreach program designed to provide small and/or minority-owned public sector organizations support in the form of business intelligence, technical expertise, and marketing strategies. With cloud-based solutions and experience, various public institutions globally have seen continued success in government, educational, and nonprofit sectors. While the funding provided can help significantly to meet business objectives, the expertise on navigating the cloud and how to extend outwards towards customers is just as critical.

Best Practices for Using AWS Systems Manager

Best Practices for Using AWS Systems Manager

As newer users adopt the AWS cloud, it can be difficult to watch for issues and resolve them as needed. AWS Systems Manager grants better visibility over the AWS environment by clustering resources, providing legible and usable data based on performance, and actions to take that abide by AWS compliance requirements and best practices. This service provides everything management needs to evaluate the cloud and ensure continued functionality.