受信した添付ファイルをGoogleドライブに保存するGAS

GAS

スクリプトは V8 ランタイム設定

[プロジェクトの設定] で V8 ランタイムを無効にしします。

ライブラリ設定

スクリプトID:
1xIy9FJeS3UtzAAW1j5fK2dZaiWxCdfy8cPT6yIdkfJSlBv7z7bxMmQZl

var searchCondition = 'is:unread has:attachment subject:{' + "【件名】" + '} replyto:{' + "メアド@×××.com" + '}'; //検索条件(添付ファイルあり);
var FOLDER      = DriveApp.getFolderById('保存先フォルダID'); //保存先フォルダID
var POSTURL     = "WebhookのURL"; //通知先チャットのURL
var pass        = "Password"

function getNewMail() {

  var threads = GmailApp.search(searchCondition, 0, 1); // search件数
 
  for (var i = 0 ; i < threads.length; i++) {
    var msgs = GmailApp.getMessagesForThread(threads[i]);
 
    for (var j = 0; j < msgs.length; j++) {
      var attachmentDate    = Utilities.formatDate(msgs[j].getDate(),"JST", "yyyy-MM-dd hh:mm:ss"); // 受信日時
      var attachmentFrom    = msgs[j].getFrom();           //送信元
      var attachmentSubject = msgs[j].getSubject();        //添付ファイル(タイトル)
      var attachments       = msgs[j].getAttachments();    //添付ファイル 
      
      var createFiles = FOLDER.createFile(attachments[0]);
      var zipfileid = createFiles.getId();
      // ZIPファイルを解凍
      var blob = DriveApp.getFileById(zipfileid).getBlob();
      var res = UnzipGs.unzip(blob, { password: pass }); // or UnzipGs.unzip(blob); 
      // ZIPファイル中のファイル
      var flsts = "";
      for(var k = 0; k < res.length; k++){
        var newFolder = FOLDER.createFile(res[k]);
        flsts = flsts + "\n" + "filename: " + newFolder.getName() + "\n" + "URL : " + newFolder.getUrl() + "\n";
      }

      if (flsts !== ""){
        createFiles.setTrashed(true); // ZIPファイル削除
        // メッセージ作成
        var msgbody = attachmentDate + "\n" +
                      attachmentSubject + "\n" +
                      "保存先フォルダのURL: " + FOLDER.getUrl() + "\n" +
                      flsts ;
        postoptions(msgbody);
      }
    } 
    // スレッドを既読にする
    threads[i].markRead();
  }
}

/**POSTメソッドのオプション*/
function postoptions (msg) {
  var options = {
    'method'  : 'POST',
    'headers' : {'Content-Type': 'application/json; charset=UTF-8'},
    'payload' :JSON.stringify({'text' : msg}),
    "muteHttpExceptions" : true
  }
  //通知を送る
  var response = UrlFetchApp.fetch(POSTURL, options); 
  try{
    // 通知
    if (response.getResponseCode() == 200){
      //判断フラグ
      response_flg = 0;
    }
  } catch (e){
    response_flg = 1;
    console.log("通知エラー" + e.messages); 
  } 
  return response_flg;
};

コメント