Process Attachments from DMARC Reporting Emails

Below is the Google App Script code I wrote to process emails and save attachments.  The purpose is stated in the comments at the top of the function below.  Using a unique Gmail inbox to gather data for a specific purpose and programmatically convert that data for my needs is very valuable.  Specifically, this program is the first of three that will (1) get XML files from emails, (2) convert those XML files into CSV files, and (3) upload those CSV files to Google's BigQuery service.  From there I can query the data with BigQuery and develop a dashboard using Google Looker.

//
// This function processes emails in the Inbox and saves ZIP, GZ, and XML files
// to Google Drive. This was developed to process DMARC files sent by receiving
// email servers that have implemented DMARC. DMARC is Domain-based Message
// Authentication Reporting & Conformance and it leverages the SPF and DKIM
// email authentication protocols.
//
function AttachmentsToDrive() {
savefolder = DriveApp.getFoldersByName("ToBeParsed").next();
var start = 0;
emails = 0;
attachs = 0;
// Get up to 50 emails from the inbox
var threads = GmailApp.getInboxThreads(start, 50);
// Process each email
for (var i = 0; i < threads.length; i++) {
emails++;
var message = threads[i].getMessages();
for (var m = 0; m < message.length; m++) {
message[m].star();
threads[i].markRead();
var subject = message[m].getSubject();
var att = message[m].getAttachments();
// Process each attachment int he email
for (var j=0; j<att.length; j++) {
attachs++;
var type = att[j].getContentType();
// If the attachment is a ZIP file, unzip it and add each attachment to Google Drive
if (type.indexOf("application/zip")>-1) {
att[j].setContentType('application/zip');
var files = Utilities.unzip(att[j]);
for (var k=0; k<files.length; k++) {
var attachname = files[k].getName();
Logger.log(attachname);
try {file = savefolder.createFile(files[k]);}
catch (e) {Logger.log(e.toString());}
}
}
// If the attachment is a GZ file, uncompress it and add it to Google Drive
if (type.indexOf("application/gzip")>-1) {
att[j].setContentType('application/x-gzip');
var blob = Utilities.ungzip(att[j]);
Logger.log(blob.getName());
blob.setContentType('application/xml');
try {file = savefolder.createFile(blob);}
catch (e) {Logger.log(e.toString());}
}
// If the attachment is an XML file, add it to Google Drive
if (type.indexOf("application/xml")>-1) {
try {file = savefolder.createFile(att[j]);}
catch (e) {Logger.log(e.toString());}
}
}
// Move the email to the Archive
threads[i].moveToArchive();
}
}
Logger.log('Number of emails processed: ' + emails);
Logger.log('Number of attachments processed: ' + attachs);
}

Upload CSV Files to Google BigQuery

This Google App Script gets each file in the "ToBeUploaded" folder in Google Drive and creates a Google BigQuery load job with tha...