gmail gasで一定期間経過したメールを自動で削除する
- 作成日 2022.09.07
- Google Apps Script
- Google Apps Script
GAS(Google Apps Script)で、gasで一定期間経過したメールを自動で削除する手順を記述してます。
環境
- OS windows11 home
- ブラウザ chrome 104.0.5112.101
処理のイメージ
処理のイメージは、以下となります。
ソースコード
まずは以下に、アクセスしてgasを開きます。
https://script.google.com/メールを自動で削除するには、トリガーに以下のスクリプトを登録して使用します。
※一度に削除できるのは500件までのようです。
function delOldGmails() {
let msg = "";
let queries = [
'category:forums', // フォーラムタブ
'category:promotions', // プロモーションタブ
'is:unread', // 未読
'in:drafts', // 下書き
'in:spam', // 迷惑メール
'has:attachment', // 添付ファイル
// 'from:xxx@xxxx', // 特定メール
];
Logger.log('削除開始');
try {
for (const query of queries) {
msg = msg + '\n' + query + 'を削除開始\n';
// 30日前以上前のメールかつ、スターと重要がついていないもの
let rule = '' + query + ' older_than:30d -is:(starred OR important)'
let mails = GmailApp.search(rule);
msg = msg + '\n該当メール数:' + mails.length + '件\n';
Logger.log(query + '該当メール数: ' + mails.length + '件');
for (const item of mails) {
item.moveToTrash(); // ゴミ箱に移動
}
Logger.log('処理終了')
}
}
catch (e) {
msg = msg + e + '\n'; // エラー発生時のメッセージ
}
finally {
sendMail(msg);
}
}
function sendMail(msg) {
const recipient = Session.getActiveUser().getEmail(); // 送信先(自分のアドレス)
const subject = 'メール削除バッチ通知'; // 件名
const recipientName = Session.getActiveUser().getUserLoginId(); // メール本文 受信者名(id)
const body = `${recipientName}様\n`
+ msg
+ '\n完了しました\n'; //本文
const options = { name: 'mebee' }; //送信者の名前
GmailApp.sendEmail(recipient, subject, body, options);
}
削除する条件は、以下のものが指定できます。
コード | 内容 |
---|---|
from: | 送信者 from:xxx@xxx |
to: | 受信者 to:xxx@xxx |
cc: | Cc cc:xxx@xxx |
bcc: | Bcc Bcc:xxx@xxx |
subject: | 件名 subject:お知らせ |
filename: | 添付ファイル名 filename:foo.xlsx |
OR | OR条件 -is:(starred OR important) |
半角スペース | AND条件 older_than:5d -is:starred |
– | NOT条件 -is:starred |
is:unread | 未読 |
is:read | 既読 |
is:important | 重要 |
is:starred | スター付き |
is:sent | 送信済み |
in:anywhere | アカウント内すべて |
in:drafts | 下書き |
in:spam | 迷惑メール |
in:trash | ゴミ箱 |
has:attachment | 添付ファイル |
has:spreadsheet | スプレッドシートリンク |
has:drive | ドライブリンク |
after: | 指定日以降を検索 after:2022/07/07 |
before: | 指定日以前を検索 before:2022/07/07 |
トリガーに登録
あとは、トリガーに登録すれば定期的にゴミ箱に移動させることが可能になります。
ここでは、毎日9~10時に設定してます。
-
前の記事
javascript エラー「SyntaxError: Unexpected token ‘**’. Ambiguous unary expression in the left hand side of the exponentiation expression; parentheses must be used to disambiguate the expression.」の解決方法 2022.09.07
-
次の記事
javascript 円周率を取得する 2022.09.07
コメントを書く