概要
- Geminiを用いてGoogleの各サービスの連携方法を学ぶ
- 毎日のメールの中で必要なメールのみ抽出する
- 朝一のメールチェックを効率化する
手順 / ノウハウ
-
GASに自身のアカウントでログインする
https://script.google.com/u/0/home?pageId=none -
レフトナビメニューから「新しいプロジェクト」を選択
-
右側のエディタに以下のサンプルコードを入力する
(例:前日のメールから重要メール(特定キーワードを含む)を取得) -
プロジェクトの名前を設定し、「ドライブにプロジェクトを保存」を選択する
-
実行ボタンを押す
- 出力結果から昨日のメールを確認できる
- ※ サンプルコードの
result.pushの部分を編集することで、ログ出力フォーマットを自由に変更可能 - ※ サンプルコードの[条件①:キーワード]を任意に編集可能
- ※ 初回実行時は自身のアカウントで承認が必要
-
トリガーを設定すれば毎日の自動実行が可能(※トリガー設定は別記事で紹介)
サンプル / テンプレート
サンプルコード
function listImportantMailsOfYesterdayToSheet() {
const tz = Session.getScriptTimeZone();
const now = new Date();
// 今日0:00
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
// 昨日0:00
const yesterdayStart = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate() - 1
);
const afterStr = Utilities.formatDate(yesterdayStart, tz, 'yyyy/MM/dd');
const beforeStr = Utilities.formatDate(todayStart, tz, 'yyyy/MM/dd');
// Gmail の検索(昨日 & inbox)
const query = `after:${afterStr} before:${beforeStr} in:inbox`;
const threads = GmailApp.search(query, 0, 200);
// 条件①:キーワード
const importantKeywords = ["重要", "返信", "提案", "支払"];
const results = [];
threads.forEach(thread => {
const messages = thread.getMessages();
messages.forEach(message => {
const msgDate = message.getDate();
// 日付チェック(スレッド単位検索のズレ対策)
if (!(msgDate >= yesterdayStart && msgDate < todayStart)) return;
const subject = message.getSubject() || "";
const body = message.getPlainBody() || "";
const from = message.getFrom() || "";
let isImportant = false;
// ① キーワード判定
for (const kw of importantKeywords) {
if (subject.includes(kw) || body.includes(kw)) {
isImportant = true;
break;
}
}
// ② label:important 判定
if (!isImportant && message.isImportant && message.isImportant()) {
isImportant = true;
}
if (!isImportant) return;
// URL生成
const url = `https://mail.google.com/mail/u/0/#all/${message.getId()}`;
results.push([
null, // 項番はあとで振る
Utilities.formatDate(msgDate, tz, 'yyyy/MM/dd HH:mm:ss'),
subject,
`=HYPERLINK("${url}", "リンク")`
]);
});
});
// データ出力
results.forEach((row, index) => {
row[0] = index + 1; // 項番振り
Logger.log(`出力完了:${row}`);
});
Logger.log(`出力完了:${results.length}件`);
}