将附件从 Gmail 复制到 Google 云端硬盘文件夹并使用 Apps 脚本覆盖旧文件

Copying attachments from Gmail to Google Drive folder and overwriting old files with Apps Script

我正在尝试使用 Google Apps 脚本自动将附件从 Gmail 收件箱下载到帐户 Google 驱动器上的特定文件夹。我发现下面的代码可以很好地完成这一部分,但我还需要它用新文件覆盖同名文件或删除旧文件并上传新文件。此外,当我只需要复制 .xlsx 文件时,它似乎仍在从具有多个附件的电子邮件中下载所有文件类型。任何帮助将非常感激。 (感谢 googleappsscript.org 获取代码)

// GLOBALS
//Array of file extension which you would like to extract to Drive
var fileTypesToExtract = ['jpg', 'tif', 'png', 'gif', 'bmp', 'svg'];
//Name of the folder in google drive i which files will be put
var folderName = 'GmailToDrive';
//Name of the label which will be applied after processing the mail message
var labelName = '@indrive';



function GmailToDrive(){
  //build query to search emails
  var query = '';
  //filename:jpg OR filename:tif OR filename:gif OR fileName:png OR filename:bmp OR filename:svg'; //'after:'+getDateNDaysBack_(1)+
  for(var i in fileTypesToExtract){
    query += (query === '' ?('filename:'+fileTypesToExtract[i]) : (' OR filename:'+fileTypesToExtract[i]));
  }
  query = 'in:inbox has:nouserlabels ' + query;
//  query += ' after:'+getDateNDaysBack_(1);
  var threads = GmailApp.search(query);
  var label = getGmailLabel_(labelName);
  var parentFolder;
  if(threads.length > 0){
    parentFolder = getFolder_(folderName);
  }
  var root = DriveApp.getRootFolder();
  for(var i in threads){
    var mesgs = threads[i].getMessages();
    for(var j in mesgs){
      //get attachments
      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 file = DriveApp.createFile(attachmentBlob);
        parentFolder.addFile(file);
        root.removeFile(file);
      }
    }
    threads[i].addLabel(label);
  }
}

//This function will get the parent folder in Google drive
function getFolder_(folderName){
  var folder;
  var fi = DriveApp.getFoldersByName(folderName);
  if(fi.hasNext()){
    folder = fi.next();
  }
  else{
    folder = DriveApp.createFolder(folderName);
  }
  return folder;
}

//getDate n days back
// n must be integer
function getDateNDaysBack_(n){
  n = parseInt(n);
  var date = new Date();
  date.setDate(date.getDate() - n);
  return Utilities.formatDate(date, Session.getScriptTimeZone(), 'yyyy/MM/dd');
}

function getGmailLabel_(name){
  var label = GmailApp.getUserLabelByName(name);
  if(!label){
    label = GmailApp.createLabel(name);
  }
  return label;
}

//this function will check for filextension type.
// and return boolean
function checkIfDefinedType_(attachment){
  var fileName = attachment.getName();
  var temp = fileName.split('.');
  var fileExtension = temp[temp.length-1].toLowerCase();
  if(fileTypesToExtract.indexOf(fileExtension) !== -1) return true;
  else return false;
}

您在脚本中注释掉了 inDefinedType 功能。

关于替换文件内容或删除同名文件,您可以

使用 getFilesByName() 查找 parentFolder 中的所有文件并删除所有旧文件。

这是一个示例代码:

// GLOBALS
//Array of file extension which you would like to extract to Drive
var fileTypesToExtract = ['xlsx'];
//Name of the folder in google drive i which files will be put
var folderName = 'GmailToDrive';
//Name of the label which will be applied after processing the mail message
var labelName = '@indrive';

function GmailToDrive() {
  var query = '';

  for(var i in fileTypesToExtract){
    query += (query === '' ?('filename:'+fileTypesToExtract[i]) : (' OR filename:'+fileTypesToExtract[i]));
  }
  query = 'in:inbox has:nouserlabels ' + query;
  Logger.log(query);

  var threads = GmailApp.search(query);
  var label = getGmailLabel_(labelName);
  var parentFolder = getFolder_(folderName);

  for(var i in threads){
    var mesgs = threads[i].getMessages();
    for(var j in mesgs){
      //get attachments
      var attachments = mesgs[j].getAttachments();
      for(var k in attachments){
        var attachment = attachments[k];
        Logger.log(attachment.getName());
        Logger.log(attachment.getContentType())

        //Check if attached file is xlsx file
        if(attachment.getContentType() == MimeType.MICROSOFT_EXCEL){
          var attachmentBlob = attachment.copyBlob();

          //Check if filename exist in the drive folder then remove the file
          var files = parentFolder.getFilesByName(attachment.getName());
          while (files.hasNext()) {
            var file = files.next();
            Logger.log("FILE EXIST. Removing.....");
            //Remove existing file
            file.setTrashed(true);
          }
          
          //Create a new file in the drive folder
          var newFile = parentFolder.createFile(attachmentBlob);
        }
      }
    }
    threads[i].addLabel(label);
  }
}

function getGmailLabel_(name){
  var label = GmailApp.getUserLabelByName(name);
  if(!label){
    label = GmailApp.createLabel(name);
  }
  return label;
}

//This function will get the parent folder in Google drive
function getFolder_(folderName){
  var folder;
  var fi = DriveApp.getFoldersByName(folderName);
  if(fi.hasNext()){
    folder = fi.next();
  }
  else{
    folder = DriveApp.createFolder(folderName);
  }
  return folder;
}

修改完成: