全体の流れ(最短ルート)
- Gmail で検索クエリ文字列を確認
- Google Apps Script を作成
- 実行
- ダウンロード
Gmail で検索クエリ文字列を確認
といっても大したことではなくたとえば、ラベルの「おしごと」をクリックしたら
クエリ編集エディットに「label:おしごと」とでてくるのでそれを保存。
Google Apps Script を作成
https://script.google.com/ を開き、新規プロジェクトを作成。
以下のコードを そのままコピペ。
function exportMailsToText() {
const QUERY = 'label:おしごと'; // ★★★ ここを書き換え
let mails = [];
const threads = GmailApp.search(QUERY);
threads.forEach(thread => {
thread.getMessages().forEach(msg => {
mails.push({
date: msg.getDate(),
from: sanitize(msg.getFrom()),
to: sanitize(msg.getTo()),
subject: sanitize(msg.getSubject()),
body: msg.getBody(),
id: msg.getId()
});
});
});
mails.sort((a, b) => a.date - b.date);
const lines = mails.map(m => {
const dateStr = Utilities.formatDate(
m.date,
Session.getScriptTimeZone(),
"yyyy-MM-dd HH:mm:ss"
);
return [
`----------------------------------------`,
`Date: ${dateStr}`,
`From: ${m.from}`,
`To: ${m.to}`,
`Subject: ${m.subject}`,
`Message-ID: ${m.id}`,
`\`\`\``,
`${m.body}`,
`\`\`\``,
].join("\n");
});
const text = lines.join("\n\n");
const fileName = `gmail_export_sorted_${Date.now()}.txt`;
DriveApp.createFile(fileName, text, MimeType.PLAIN_TEXT);
Logger.log("作成したファイル名: " + fileName);
}
function sanitize(text) {
if (!text) return "";
return text.replace(/[\x00-\x1F\x7F]/g, "");
}
ダウンロード
AppsScript の上記スクリプトをペーストした編集部分の上にある 「|> 実行」をクリック。
権限を要求されるので、許可。
ダウンロード
Google Drive に保存されるのでダウンロードする。