0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【GAS】Gmailの添付ファイルをGoogleドライブへ自動保存しスプレッドシートに台帳記録する方法(重複防止対応)

0
Posted at

はじめに
Gmailで受け取った請求書や領収書などの添付ファイルを、Google Apps Script(GAS)を使ってGoogleドライブの指定フォルダへ自動抽出し、スプレッドシートに履歴台帳を記録する仕組みを解説します。

処理の全体フロー
GmailApp.search() で指定した検索条件(例: has:attachment -label:保存済み)のメールスレッドを取得

各メッセージから getAttachments() で添付ファイルを取得

DriveApp.getFolderById().createFile() で指定フォルダへ直接書き出し

SpreadsheetApp.appendRow() で受信日時・送信者・ファイル名・URLを記録

重複処理を防ぐため、スレッドに addLabel() で完了ラベルを付与

コアロジック(サンプルコード)

function saveAttachments() {
const folder = DriveApp.getFolderById('YOUR_FOLDER_ID');
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const label = GmailApp.getUserLabelByName('保存済み') || GmailApp.createLabel('保存済み');

const threads = GmailApp.search('has:attachment -label:保存済み', 0, 10);

threads.forEach(thread => {
thread.getMessages().forEach(message => {
message.getAttachments().forEach(att => {
const file = folder.createFile(att);
sheet.appendRow([message.getDate(), message.getFrom(), att.getName(), file.getUrl()]);
});
});
thread.addLabel(label);
});
}

完全版コード・導入手順について
スプレッドシートUIメニュー連携、エラーハンドリング、カスタム検索フィルタに対応した完全版スクリプトと導入マニュアルは note(B2B Tools) にて公開しています。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?