LoginSignup
3
2

More than 1 year has passed since last update.

Gmailで古いどうでも良いメールを定期的に削除する

Last updated at Posted at 2022-01-12

用途

あまり重要でないメールを定期的に掃除します

仕様

  • 手動で実行,または定期的に自動で実行します
  • 100日以上経ったメールのうち「プロモーション」に分類され,重要フラグまたはスターフラグが付いていないものを削除します
  • 削除を分割して繰り返すのはGoogleのマニュアルにそうするように書いてあったため

使い方

  1. https://script.google.com にてスクリプトを新規作成
  2. 左メニューの「スクリプトの設定」で「appscript.jsonマニフェストをエディタで表示」にチェック
  3. エディタに戻ってコード.gsとappscript.jsonを入力,保存
  4. purgeMails()を実行してみるとGmailへのアクセス許可を求められるので許可する
  5. activate()を一度実行すると定期的に実行するトリガーが設定されます
コード.gs
// トリガーの設定
function activate() {
  ScriptApp.newTrigger("purgeMails")
           .timeBased().everyDays(1).create();
}

// トリガーの取り消し
function deactivate() {
  ScriptApp.getScriptTriggers()
            .forEach(tirgger => ScriptApp.deleteTrigger(trigger));
}

// メールの削除
function purgeMails() {
  const daysToKeep = 100; // 保存期間

  // 日付文字列の生成
  let day = new Date();
  day.setDate(day.getDate() - daysToKeep);
  const dateString = day.getFullYear() + "/" + (day.getMonth() + 1) + "/" + day.getDate();

  // 削除条件
  let criteria = [
    "before:" + dateString,
    "category:promotions",
    "-label:important",
    "-is:starred"
  ];
  criteria = "(" + criteria.join(" ") + ")";
  let threads = [0];

  // 残り0になるまでメール削除
  while(threads.length > 0) {
    threads = GmailApp.search(criteria, 0, 500);
    Logger.log("purgeMails: " + criteria + " => " + threads.length + "threads");
    threads.forEach(thread => thread.moveToTrash());
  }
}
appscript.json
{
  "timeZone": "Asia/Tokyo",
  "dependencies": {
  },
  "oauthScopes": [
      "https://mail.google.com/",
      "https://www.googleapis.com/auth/script.scriptapp"
    ],
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8"
}

参考

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