はじめに
Gmailに届くメールには、多くの場合、重要な情報が含まれた添付ファイルが付いています。手動でこれらのファイルをダウンロードし、情報を抽出するのは手間がかかります。この記事では、Google Apps Scriptを用いて、Gmailに届いたPDFファイルから自動的に情報を抽出し、Googleドライブに保存する方法をご紹介します。
スクリプトの概要
今回紹介するスクリプトでは、以下のステップを実行します:
- 指定された件名と添付ファイルを含むGmailスレッドを検索。
- PDFファイルをGoogleドライブに保存。
- PDFから必要な情報(例えば、日付、金額、番号など)を抽出。この例では、「〇〇円」を抽出します。
- 抽出した情報を元にファイル名を付けて保存。
事前準備
Google Apps Scriptを使用する際には、以下の設定が必要です。プロジェクトの設定ファイルで、タイムゾーンや依存関係、OAuthスコープを設定します。
{
"timeZone": "Asia/Tokyo",
"dependencies": {
"enabledAdvancedServices": [
{
"userSymbol": "Drive",
"version": "v3",
"serviceId": "drive"
}
]
},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8",
"oauthScopes": [
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/script.scriptapp",
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/documents",
"https://www.googleapis.com/auth/gmail.readonly",
"https://www.googleapis.com/auth/spreadsheets"
]
}- timeZone: スクリプトのタイムゾーンを設定します。この例では、
Asia/Tokyoを設定しています。 - enabledAdvancedServices: ここでは、Google Drive APIを使用するために
Driveサービスを有効化しています。 - exceptionLogging: 例外発生時のログを記録するサービスを指定します。
STACKDRIVERを使用しています。 - runtimeVersion: スクリプトのランタイムバージョンを指定します。
V8を使用しています。 - oauthScopes: スクリプトがアクセスする権限を設定します。Gmail、Google Drive、Google Docs、Google Spreadsheetsへのアクセス権限を指定しています。
詳細な手順
- Gmailスレッドの検索
指定された条件に合うGmailスレッドを検索し、添付ファイルを抽出します。 - PDFファイルの保存
添付ファイルをGoogleドライブに保存します。 - PDFから情報の抽出
PDFファイルから「〇〇円」という形式の金額情報を抽出します。これを実現するために、PDFをGoogleドキュメントに変換し、テキストを解析します。 - ファイル名の付与と保存
抽出した金額情報を元に、ファイル名を付けてGoogleドライブに保存します。
サンプルコード
以下に、PDFファイルから金額情報(「〇〇円」)を抽出するためのサンプルコードを示します。
function extractAndSaveEmailAttachments() {
const query = 'subject:"請求書" has:attachment';
const threads = GmailApp.search(query);
threads.forEach(thread => {
thread.getMessages().forEach(message => {
message.getAttachments().forEach(attachment => {
if (attachment.getContentType() === 'application/pdf') {
const file = DriveApp.createFile(attachment.copyBlob());
const extractedData = extractAmount(file);
if (extractedData) {
const fileName = `Invoice_${extractedData}.pdf`;
file.setName(fileName);
Logger.log(`ファイル名: ${fileName}`);
}
}
});
});
});
}
function extractAmount(file) {
const docId = convertPdfToGoogleDoc(file.getId());
if (docId) {
const text = extractTextFromGoogleDoc(docId);
const amount = extractAmountFromText(text);
DriveApp.getFileById(docId).setTrashed(true); // 一時的なGoogleドキュメントを削除
return amount;
}
return null;
}
function convertPdfToGoogleDoc(fileId) {
const file = DriveApp.getFileById(fileId);
const blob = file.getBlob();
const resource = {
title: file.getName(),
mimeType: MimeType.GOOGLE_DOCS
};
const options = {
method: 'post',
contentType: 'application/pdf',
payload: blob,
convert: true
};
const response = Drive.Files.insert(resource, blob, options);
return response.id;
}
function extractTextFromGoogleDoc(docId) {
const doc = DocumentApp.openById(docId);
const body = doc.getBody();
return body.getText();
}
function extractAmountFromText(text) {
const amountRegex = /¥([\d,]+円)/;
const match = text.match(amountRegex);
return match ? match[0] : null;
}
このスクリプトでは、Gmailの特定の件名に基づいてメールを検索し、PDF添付ファイルをGoogleドライブに保存します。その後、PDFファイルをGoogleドキュメントに変換し、テキストから金額情報を抽出します。抽出した情報を基にファイル名を設定して保存します。