【GAS】Googleフォーム添付ファイルの有無に応じてメールを送信する方法

Googleフォーム

Googleフォーム関連

ご訪問ありがとうございます。

Googleシートマスターのひろしです。

前回

【GAS】Googleフォームに添付された複数のファイルを特定の送信先に送る
Googleフォームに添付された複数のファイルを自動的に指定のメアドに送ることができます。

今回は、とっても価値の高い方法をお伝えします。


これを知ることであなたは、

  • Googleフォームで指定された添付ファイルを特定のメアドに送信することができます。
  • 添付ファイルの有無に関わらず送信できます。
  • ロジック変更時のちょっとしたテクニックが身につきます。

添付ファイルの有無に応じてメールの添付ファイルを制御できます。

ロジックの変更時における考え方がわかります。

 

なので、サクッとマスターして

と答えてあげてください。

動画はこちら

【GAS】Googleフォーム添付ファイルの有無に応じてメールを送信する方法

フォームはこちら

Google Forms: Sign-in
Access Google Forms with a personal Google account or Google Workspace account (for business use).

*クリックすることでシートが開きます。

 

スクリプト

function sendForm(e) {


  const to = "futoshita.hiroshi@gmail.com"


  // const to = e.response.getRespondentEmail()   //「このフォームでは回答者のメールアドレスを収集しています。」のメアド


  // 件名
  const subject = "報告書が記入されました"
  // 本文
  let body = "内容は下記の通りです。"


  let itemResponses = e.response.getItemResponses()



  let attachImg1 = "" //添付ファイル1
  let attachImg2 = ""//添付ファイル2



  for (var i = 0; i < itemResponses.length; i++) {
    var itemResponse = itemResponses[i];
    var type = itemResponse.getItem().getType();
    var question = itemResponse.getItem().getTitle();
    var answer = itemResponse.getResponse();


    if (question == "添付ファイル1") {
      attachImg1 = DriveApp.getFileById(answer).getBlob();
    }
    if (question == "添付ファイル2") {
      attachImg2 = DriveApp.getFileById(answer).getBlob();
    }
    // 回答項目
    body += "\n\n【" + question + "】\n\n";
    // 回答内容
    body += answer;



  }


  let options = ""




  if (attachImg1 && attachImg2) { //添付ファイルが2つある場合
    options = {
      "attachments": [attachImg1, attachImg2]
    }
  }
  else {
    if (attachImg1) { //添付ファイル1のみ
      options = { "attachments": attachImg1 }
    }
    if (attachImg2) {//添付ファイル2のみ
      options = { "attachments": attachImg2 }
    }
  }




  if (options) {  //添付ファイルがあり
    MailApp.sendEmail(to, subject, body, options)
  }
  else {          //添付ファイルなし
    MailApp.sendEmail(to, subject, body)
  }



}
検証用スクリプト


function test() {






  let attachImg1 = "a" //添付ファイル1
  let attachImg2 = "b"//添付ファイル2



  let options = ""



  if (attachImg1 && attachImg2) { //添付ファイルが2つある場合
    options = {
      "attachments": [attachImg1, attachImg2]
    }
  }
  else {
    if (attachImg1) { //添付ファイル1のみ
      options = { "attachments": attachImg1 }
    }
    if (attachImg2) {//添付ファイル2のみ
      options = { "attachments": attachImg2 }
    }
  }




  if (options) {  //添付ファイルがあり



    console.log(options)
    // MailApp.sendEmail(to, subject, body, options)
  }
  else {          //添付ファイルなし
    console.log("添付ファイルなし")
    // MailApp.sendEmail(to, subject, body)
  }


}

最後までご覧いただきありがとうございます。

つぎはこちら

Googleフォームの登録をLINEに通知する方法
Googleフォームにおける自動返信メールの設定およびLINEに通知する設定が行なえます。

中級関数の一覧

コメント

タイトルとURLをコピーしました