LoginSignup
1
1

More than 5 years have passed since last update.

【GAS】Gメールでファイルを添付して自動返信

Posted at

概要

  • GASの時間主導型トリガーで動く
  • Gメールで未読のメールについてfizzbuzzを含むものを検索
  • 見つかったらhogeフォルダのファイルを添付して送信
  • 既読をつけて終了

コード


function main() {
  autoReply('(is:unread "fizzbuzz")', //未読かつfizzbuzzを含むもの
            'タイトル',
            'メールを受け取りました。',
            getFilesByFolderName('hoge');
           );
}

function autoReply(str, subject, body, files) {
  var mails = GmailApp.getMessagesForThreads(GmailApp.search(str)); //検索と配列へ変換

  if(mails.length == 0) //メールがなければ終了
    return;

  mails.map(function (mail) {
    MailApp.sendEmail({
    to: mail[0].getFrom(),
    subject: subject,
    body: body,
    attachments: files
    });

    mail[0].markRead(); //既読付け
  });
}

//フォルダの名前から検索して中のファイルを配列で返す
function getFilesByFolderName(folderName) {
  var folder = DriveApp.getFoldersByName(folderName).next();
  return iteratorToArr(folder.getFiles());
}

function iteratorToArr(files) {
  var arr = [];

  while(files.hasNext()) {
    arr.push(files.next());
  }

  return arr; 
}

問題点

  • getFilesByFolderNameや添付フォルダの検索はメールの有無を確認してからした方がよさそう
  • Gmail側で誤って既読を未読に変更したら再送信されてしまう。
  • また、GASが動く前にうっかりメールを見てしまうと既読になり自動送信してくれない。
  • フォルダの名前がかぶるとまずい。IDで指定すればいい。

参考資料

Class GmailApp  |  Apps Script  |  Google Developers
【GAS】新たな問い合わせメールをGmailで取得しスプレッドシートに随時追加する

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1