LoginSignup
0
0

More than 1 year has passed since last update.

GASでGmailで指定の件名のメールから毎日決まった時間に添付ファイルをGoogle Driveに保存する方法

Last updated at Posted at 2022-06-17

ポイント

  • Google driveの保存するフォルダと紐づける
  • 指定する件名を設定する
  • 今日と明日の日付を取得し件名の検索に加える
  • 自動で実行するタイミングを設定する

方法

function saveAttachment() {

    //取得するメールタイトルを指定
    let mail_title = '"eFax メッセージ"';

    // 今日の日付取得準備
    let date = new Date();
    // 今日の日付を定義
    let today = Utilities.formatDate(date, "JST","yyyy/M/d");
    //console.log (today);

    // 明日の日付取得準備
    let asu = new Date();
    //明日の日付を取得
    asu.setDate(date.getDate() + 1);
    //明日の日付を定義
    let tomorrow = Utilities.formatDate( asu, 'JST', 'yyyy/M/dd');
    //console.log(tomorrow);

     //検索マッチ条件、添付ファイルあり、今日〜明日のメール
     let query = 'has:attachment subject:(' + mail_title + ') after:('+ today + ') before:('+ tomorrow + ')';

     //指定条件でスレッド化
     let threads = GmailApp.search(query);

     //保存先のフォルダID
     let folderId = '自分の指定したいドライブのID';
      
     //スレッド化したメールの件数分繰り返し 
     threads.forEach(function(thread) {
      // スレッド内のメール一覧を取得
      let messages = thread.getMessages();
        
      // メールを一つずつ取り出す
      messages.forEach(function(message) {
      // 添付ファイルを取得
      let attachments = message.getAttachments();

          //添付ファイルの受信日付
          let date = Utilities.formatDate(message.getDate(), 'Asia/Tokyo', 'yyyyMMdd');

          attachments.forEach(function(attachment){
      
            //日付を加えたファイル名用意
            let fileName = date +'_'+ attachment.getName();
            attachment.setName(fileName);
          
            // ドライブに保存  
            DriveApp.getFolderById(folderId).createFile(attachment);
            //ファイル名を上書き
     })
    });
  });
}
0
0
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
0
0