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】Googleスプレッドシートの行データから個別PDFを一括生成してGmailで一括送信する方法(誤送信防止機能付き)

0
Posted at

はじめに
スプレッドシート上の顧客一覧データを読み込み、Googleドキュメントのテンプレートを用いて個別のPDF(請求書や案内状など)を自動作成し、そのままメール添付で送信する仕組みをGASのみで構築します。

処理ロジックとフロー
SpreadsheetApp でシートの全行データを一括取得

ドキュメントテンプレート(DriveApp.getFileById())を複製し、body.replaceText() で {{項目名}} を動的置換

getAs('application/pdf') でPDF変換し、指定フォルダへ格納

GmailApp.sendEmail() でPDFを添付して送信

スプレッドシートの「送信ステータス」列を「送信完了」に更新して重複・誤送信を防止

ソースコード(コア部分)

function generatePdfAndSend() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const data = sheet.getDataRange().getValues();
const templateFile = DriveApp.getFileById('YOUR_TEMPLATE_ID');
const folder = DriveApp.getFolderById('YOUR_FOLDER_ID');

for (let i = 1; i < data.length; i++) {
const [name, email, amount, invNo, status] = data[i];
if (status === '送信完了' || !email) continue;

// テンプレート複製&置換
const copy = templateFile.makeCopy(`Invoice_${name}`, folder);
const doc = DocumentApp.openById(copy.getId());
doc.getBody().replaceText('{{顧客名}}', name);
doc.getBody().replaceText('{{金額}}', amount);
doc.saveAndClose();

// PDF化
const pdf = copy.getAs('application/pdf');
folder.createFile(pdf);
copy.setTrashed(true);

// Gmail送信
GmailApp.sendEmail(email, `請求書送付 (${invNo})`, `${name}様\n請求書を添付します。`, {
  attachments: [pdf]
});

sheet.getRange(i + 1, 5).setValue('送信完了');

}
}

まとめ・完全版スクリプト
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?