LoginSignup
3
11

More than 1 year has passed since last update.

【GAS】Gmailにファイルが添付されてたらGDriveに保存する

Last updated at Posted at 2019-03-23

IFTTTでGmailトリガーが廃止されると聞いて

IFTTTで使ってたのはファイルの保存だけでしたのでGASで書きました。
LINEもStackもなんでもAPI叩けばなんとでもなる思います。

GAS

function saveFilesToDriveFromGmail() {
  const folderId = '保存先フォルダーID';
  
//1時間ごとにトリガー実行1h、2時間なら2h、一日なら1d
  const keyword = 'has:attachment -is:sent newer_than:1h' 

  const myThreads = GmailApp.search(keyword, 0, 30);
  const myMsgs = GmailApp.getMessagesForThreads(myThreads);

  if(myMsgs.length == 0)
    return null;
    
  //添付ファイルの配列
  const attachments = myMsgs.reduce(function(pre, cur) {
    return pre.concat(cur.reduce(function(pre, cur) {
      return pre.concat(cur.getAttachments());
    },[]))
  },[]);
 
  attachments.map(function(file) {
    DriveApp.getFolderById(folderId).createFile(file); 
  });
}

あとがき

IFTTTのGmailトリガー廃止ですが、基本的にはGASの方が自由度が高いのでIFTTTで出来ることはGASでもできるとお思います。
実際にIFTTTでは文字化けでできなかったことをGASでは問題なくできたりしています。
【GAS】GDriveにファイルが追加されたらGmailで添付してメールする
一方で1分毎の実行が最小単位で即応性はありません。

3
11
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
3
11