1
votes

I have emails coming in containing zip files. How could I unzip and save these files to a specific folder on Google Drive using Google Apps Script? The below code part works perfectly with simple excel/pdf files.

var root = DriveApp.getRootFolder();
  for(var i in threads){
    var mesgs = threads[i].getMessages();
    for(var j in mesgs){
      var attachments = mesgs[j].getAttachments();
      for(var k in attachments){
        var attachment = attachments[k];
        var isDefinedType = checkIfDefinedType_(attachment);
        if(!isDefinedType) continue;
        var attachmentBlob = attachment.copyBlob();
                
var existingFile = DriveApp.getFilesByName(attachment.getName());
if (existingFile.hasNext()) {
  var file = existingFile.next();
  file.setTrashed(true);
}
var file = DriveApp.createFile(attachmentBlob);
parentFolder.addFile(file);
root.removeFile(file);
1

1 Answers

1
votes

Answer:

You can add files to a folder using Utilities.unzip().

Code Example:

var attachmentBlob = attachment.copyBlob();
var files = Utilities.unzip(attachmentBlob);

files.forEach(function(file) {
  DriveApp.createFile(file)
  parentFolder.addFile(file);
  root.removeFile(file);
});

References: