Skip to content

Instantly share code, notes, and snippets.

@tyru
Last active Mar 21, 2019
Embed
What would you like to do?
Google Apps Script で Gmail の添付ファイルを Google Drive に保存
// Google Drive でフォルダに移動した時のURLで分かる
// https://drive.google.com/drive/u/1/folders/{フォルダのID}
var SAVE_FOLDER_ID = 'フォルダのID';
var READ_LABEL_NAME = '添付ファイル保存済み';
var SEARCH_CONDITION = 'has:attachment -label:' + READ_LABEL_NAME;
var THREADS_PER_PAGE = 100;
function saveAttachments() {
Logger.clear();
Logger.log('start');
var folder = DriveApp.getFolderById(SAVE_FOLDER_ID);
if (!folder) {
Logger.log('Google Drive フォルダを先に作成する必要があります');
return;
}
var readLabel = GmailApp.getUserLabelByName(READ_LABEL_NAME);
if (!readLabel) {
Logger.log('Gmail ラベルを先に作成する必要があります: ' + READ_LABEL_NAME);
return;
}
for (var start = 0; true; start += THREADS_PER_PAGE + 1) {
var threads = GmailApp.search(SEARCH_CONDITION, start, THREADS_PER_PAGE);
if (threads.length === 0) {
break;
}
threads.forEach(function (th) {
// 既にラベルが貼られていたらスキップ
var labels = th.getLabels();
for (var i = 0; i < labels.length; i++) {
if (labels[i].getName() === READ_LABEL_NAME) {
Logger.log('スキップ: ' + th.getFirstMessageSubject());
return;
}
}
// Google Drive に添付ファイルを保存
th.getMessages().forEach(function (msg) {
msg.getAttachments().forEach(function (attachment) {
folder.createFile(attachment);
Logger.log('添付ファイルを保存: ' + attachment.getName());
});
});
// 保存し終わったメッセージにはラベルを貼る
th.addLabel(readLabel);
});
}
Logger.log('end');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment