function extractZipEmailsAndStoreInDrive() {
// zipファイル付きのメールを検索
var searchQuery = 'has:attachment filename:zip';
var zipThreads = GmailApp.search(searchQuery);
var messagesWithZip = [];
for (var i = 0; i < zipThreads.length; i++) {
var messages = zipThreads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var message = messages[j];
var attachments = message.getAttachments();
var hasZip = attachments.some(function(attachment) {
return attachment.getContentType() === 'application/zip';
});
if (hasZip) {
messagesWithZip.push(message);
}
}
}
var relatedEmails = [];
var emailIds = messagesWithZip.map(function(message) { return message.getId(); });
var timeBufferMinutes = 15;
var relatedSearchQueryParts = messagesWithZip.map(function(message) {
var timeFrameStart = new Date(message.getDate().getTime() - timeBufferMinutes * 60 * 1000);
var timeFrameEnd = new Date(message.getDate().getTime() + timeBufferMinutes * 60 * 1000);
var sender = message.getFrom();
return '(' + 'after:' + formatDate(timeFrameStart) + ' before:' + formatDate(timeFrameEnd) + ' from:' + sender + ')';
});
var relatedSearchQuery = relatedSearchQueryParts.join(' OR ');
var relatedThreads = GmailApp.search(relatedSearchQuery);
for (var k = 0; k < relatedThreads.length; k++) {
var relatedMessages = relatedThreads[k].getMessages();
for (var l = 0; l < relatedMessages.length; l++) {
var relatedMessage = relatedMessages[l];
if (!emailIds.includes(relatedMessage.getId())) {
relatedEmails.push(relatedMessage);
}
}
}
var passwordPattern = /[A-Za-z0-9!@#$%^&*()_+]{6,}/;
var password = null;
relatedEmails.forEach(function(message) {
var body = message.getBody();
var match = body.match(passwordPattern);
if (match) {
password = match[0];
return false;
}
});
if (password) {
messagesWithZip.forEach(function(message) {
var attachments = message.getAttachments();
attachments.forEach(function(attachment) {
if (attachment.getContentType() === 'application/zip') {
var blob = attachment.copyBlob();
var unzippedFiles = Utilities.unzip(blob, password);
var folder = DriveApp.getFolderById('<YOUR_DRIVE_FOLDER_ID>');
unzippedFiles.forEach(function(file) {
folder.createFile(file);
});
}
});
});
} else {
Logger.log('No password found');
}
}
function formatDate(date) {
var year = date.getFullYear();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
var hour = ('0' + date.getHours()).slice(-2);
var minute = ('0' + date.getMinutes()).slice(-2);
return year + '/' + month + '/' + day + ' ' + hour + ':' + minute;
}
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme