皆様お世話になります。
プログラミング初心者ですが宜しくお願い申し上げます。
実現したいこと
理想としては、受信したGmailに添付されたzipファイルを解凍してGoogle driveの指定保存先に直接自動保存したいと考えております。
試したこと
いろいろと調べてみましたが実現できなかったので行程を2つに分けてみました。
とりあえず下2つのコードが動作することは確認できました。
➀まずGoogle driveにGmail添付のzipファイルを保存
GAS
1function test(){ 2 3const folderId = '(Google drive保存先フォルダID)'; 4const folder = DriveApp.getFolderById(folderId); 5 6const query = 'has:attachment'; 7const threads = GmailApp.search(query,0,1); 8const messages = threads[0].getMessages(); 9 10for (const message of messages){ 11 const attachments = message.getAttachments(); 12 13 for (const attachment of attachments){ 14 const subject = message.getSubject(); 15 const name = attachment.getName(); 16 console.log(`Subject: ${subject},Attachment: ${name}`); 17 18 folder.createFile(attachment); 19 } 20 } 21} 22
➁Google driveに保存したファイルを解凍する
GAS
1function test2(){ 2const getFileId = () => { 3const folderId = DriveApp.getFolderById('(Google drive保存先フォルダID)'); 4const files = folderId.getFiles(); 5 6 while (files.hasNext()) { 7 const file = files.next(); 8 9 const zipfileID = file.getId(); 10 11 console.log(zipfileID); 12 13 let zipFile = DriveApp.getFileById(zipfileID); 14 15 let zipFileBlob = zipFile.getBlob().setContentType('application/zip'); 16 let unzipFiles = Utilities.unzip(zipFileBlob); 17 let newFolder = folderId.createFolder('新しいフォルダ'); 18 19 for(let i = 0; i < unzipFiles.length;i++){ 20 newFolder.createFile(unzipFiles[i]); 21 } 22 } 23 } 24}
コード2つにそれぞれトリガーを設定することで自動保存は実現できそうですが、もっと簡素に1つのコードで実現が可能であればご教授宜しくお願い致します。
また、上記のコードに不備がございましたらご指摘を頂きたく宜しくお願い致します。
コード作成にあたり以下のウェブサイトを参考にさせて頂きました。
[GAS]unzip メソッドについて
【コピペで使える】GASで添付のzipファイルを展開してドライブに保存する
[GAS]Utilities.unzip()で発生するエラーの原因と解決策
非エンジニアがGmailとGoogleDriveを連携して添付ファイルを自動保存する!
あなたの回答
tips
プレビュー