はじめに
Google Spreadsheetに列挙したメールアドレスにメールを送信するGAS(Google Apps Script)です。
メール本文はGoogle Docsで作って、GASで変数を置き換えます。
送信する際は、Google Spreadsheetからスクリプトを表示して「実行」をクリックします。
環境
2024.02.19時点のバージョンです。
- Google Spreadsheet - Google Docs - Google Apps Script
Google Spreadsheet
下記のようなGoogle Spreadsheetを使います。

Google Spreadsheet
メール本文は、下記のようなGoogle Docsを使います。
差し込みに使う変数は何でもよいですが、今回は{{変数名}}のように{{と}}で囲った変数を使っています。

ソース
function postEmail() {
// 現在のスプレッドシート
var SheetName = SpreadsheetApp.getActiveSheet();
var SheetRow = SheetName.getDataRange().getLastRow();
// メール本文に適用するGoogle Docs。
// Google DocumentのURLで「/d/」と「edit」の間にある乱数をコピーする。
var docID = DocumentApp.openById('xxxxxxxxxxxxUsvezm7pfbbbucxaaaaaaaaaaa');
// メールタイトルと差出人
var mailSubject = 'テストメール';
var mailSender = 'メールのタイトル';
var mailFrom = 'xxxx@xxx.xxx';
// 変数の定義
var docData = docID.getBody().getText();
var email = '';
var passcode = '';
var body = '';
// 1行目は項目なので、2行目「2」から始める。
for (var i=2; i <= SheetRow; i++) {
// スプレッドシートのA列は「1」、B列は「2」、以下同様。
name = SheetName.getRange(i, 1).getValue();
email = SheetName.getRange(i, 2).getValue();
passcode = SheetName.getRange(i, 3).getValue();
// コンソールで送信確認
console.log(name);
console.log(email);
console.log(passcode);
// 差し込み
// 2回目以降のreplaceはbody変数に対して行う。
body = docData.replace(/{{name}}/, name);
body = body.replace(/{{passcode}}/, passcode);
// メール送信
GmailApp.sendEmail(email, mailSubject, body, {from: mailFrom, name: mailSender});
}
}


Comments