如何使用带有JavaScript的Google表格发送带有PHP的电子邮件?

时间:2019-06-17 14:11:28

标签: email google-sheets

这是有关带有表单的登录页面,该表单会将信息发送到Google表格。它正在工作,但是...

我还想使用PHP创建电子邮件确认。但是我观察到$ _POST不起作用。由于此HTML表单,我无法使用用户发送的信息。

如何在这种情况下使$ _POST工作?

我尝试使用其他Google工作表脚本(https://developers.google.com/apps-script/reference/mail/mail-app#sendEmail(String,String,String,String)

以及nodejs工具(https://www.w3schools.com/nodejs/nodejs_email.asp),但是这些方式都需要来自Google帐户的授权。这个项目我做不到。

<!doctype html>
<html lang="fr">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="../css/bootstrap.min.css">
    <link rel="stylesheet" href="../css/custom.css">

    <!-- Javascript JS -->
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="../js/bootstrap.min.js"></script>   
    <script src="https://www.googleapis.com/auth/script.send_mail"></script>
    <script src="../js/page-script-email.js"></script>

    <title>Google sheet form</title>
  </head>
  <body>



      <section id="contactformarea" class="container contact">


            <form action="index.php#foo" method="post" id="foo">

                <div class="wrapper-contact">

                    <div class="form-row justify-content-between">
                        <div class="form-group col-md-6">
                            <label for="c-prenom">Prénom</label>
                            <input type="text" class="form-control" name="c-prenom" id="c-prenom" placeholder="Prénom*" required>
                        </div>
                        <div class="form-group col-md-6">
                            <label for="c-nom">Nom</label>
                            <input type="text" class="form-control" name="c-nom" id="c-nom" placeholder="Nom*" required>
                        </div>

                    </div>

                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="c-telephone">Téléphone</label>
                            <input type="tel" class="form-control" name="c-telephone"  id="c-telephone" placeholder="Téléphone*" required>
                        </div>
                        <div class="form-group col-md-6">
                            <label for="c-email">Email</label>
                            <input type="email" class="form-control" name="c-email"  id="c-email" placeholder="Email*" required>
                        </div>
                    </div>




                    <div class="form-row">
                        <textarea name="c-message" id="c-message" class="form-control" cols="30" rows="10" placeholder="Votre message"  required></textarea>
                    </div> 

                </div><!-- fin de wrapper-contact -->

                <p class="text-right mt-3"><input type="submit" class="btn btn-primary" id="btn-valider" value="VALIDER"></p>
                <p id="feedback">Nous avons bien reçu votre demande ! <br/> Vous allez recevoir un mail de confirmation</p>

            </form>
        </div><!-- fin de wrapper-contact  -->

        <?php 
        if(isset($_POST)){
            $to      = $_POST['c-email'];
            $subject = 'le sujet';
            $message = 'Bonjour !';
            $headers = 'From: webmaster@example.com' . "\r\n" .
            'Reply-To: webmaster@example.com' . "\r\n" .
            'X-Mailer: PHP/' . phpversion();
            mail($to, $subject, $message, $headers);
        }
      ?>
      </section>

  </body>
</html>

2 个答案:

答案 0 :(得分:0)

我找到了另一个解决方案,该解决方案已经可以使用了,但是还没有!

要填写我的Google工作表,我使用以下Google脚本: https://gist.github.com/triblondon/854315a40d280a22fd89804e332fd7b3

到目前为止有效。

我想在我的Google工作表中每次创建新行时都发送一封自动电子邮件,以便与客户确认他共享的信息。

我尝试使用Google Apps脚本来实现。

function EmailConfirm(){

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];

  // récup l'index de la dernière ligne
  var lastRow = sheet.getLastRow();

  // récup le nmbre de colonnes
  var nbColumn = sheet.getLastColumn();
  var dataRange = sheet.getRange(lastRow, 1, 1, nbColumn);
  var data = dataRange.getValues();  

  for (i in data){
    var row = data[i];
    var prenom = row[1];
    var nom = row[2];
    var telephone = row[3];
    var email= row[4];
    var statut = row[5];
    var societe = row[6];
    var nbCartons = row[7];
    var nbDisplay = row[8];
    var message = row[9];
  }

  //signature mail LOGO
  var logo = "http://xxxxxxxxx";

  Logger.log(email);

  MailApp.sendEmail({
    to: email,
    from: "mail@mail.com",
    subject: "Confirmation",
    htmlBody:"<h1>Bonjour "+ prenom +", <br/>ceci est un mail de confirmation.</h1>"
    +"<p>Merci de l'intéret que vous portez à notre société.</p>"
    +"<p>Voici le récapitulatif de vos informations personnelles : </p>"
    +"<ul>"
    +"<li>Votre nom : "+ nom +"</li>"
    +"<li>Votre prénom : "+ prenom +"</li>"
    +"<li>Votre numéro de téléphone : "+ telephone +"</li>"
    +"<li>Votre statut : " + statut + "</li>"
    +"<li>Votre société : "+ societe +"</li>"
    +"<li>Et votre message : "+ message +"</li>"
    +"</ul>"
    +"<p>Nous traitons votre demande au plus vite. Merci pour votre confiance.</p>"
    +"<img src="+logo+">"
  });
}

当我手动执行此功能时,该功能也起作用。我用google apps脚本记录了有关触发器的信息。但这没用。

如何使用Google Apps脚本自动执行功能?

纪尧姆,年轻的开发人员

答案 1 :(得分:0)

我找到了一个我想分享的解决方案。 这是主要的Google Apps脚本,可帮助我从以下位置保存客户的信息: html表单。我主要受此教程的启发:http://railsrescue.com/blog/2015-05-28-step-by-step-setup-to-send-form-data-to-google-sheets/

我完成了它,以创建一封自动邮件,向客户确认他共享的数据。这是我的代码:

//  1. Enter sheet name where data is to be written below
        var SHEET_NAME = "formdata";

//  2. Run > setup
//
//  3. Publish > Deploy as web app
//    - enter Project Version name and click 'Save New Version'
//    - set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously)
//
//  4. Copy the 'Current web app URL' and post this in your form/script action
//
//  5. Insert column names on your destination sheet matching the parameter names of the data you are passing in (exactly matching case)

var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service


// If you don't want to expose either GET or POST methods you can comment out the appropriate function
function doGet(e){
  return handleResponse(e);
}

function doPost(e){
  return handleResponse(e);  
}

function handleResponse(e) {
  // shortly after my original solution Google announced the LockService[1]
  // this prevents concurrent access overwritting data
  // [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
  // we want a public lock, one that locks for all invocations
  var lock = LockService.getPublicLock();
  lock.waitLock(30000);  // wait 30 seconds before conceding defeat.

  try {
    // next set where we write the data - you could write to multiple/alternate destinations
    var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
    var sheet = doc.getSheetByName(SHEET_NAME);

    // we'll assume header is in row 1 but you can override with header_row in GET/POST data
    var headRow = e.parameter.header_row || 1;
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow()+1; // get next row
    var row = [];

    // loop through the header columns
    for (i in headers){
      if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
        row.push(new Date());
      } else { // else use header name to get data
        row.push(e.parameter[headers[i]]);
      }
    }

    // more efficient to set values as [][] array than individually
    sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);

    // AUTOMATIC CONFIRM EMAIL 
    // to get the last row
    var lastRow = sheet.getLastRow();

    // to get the number of columns
    var nbColumn = sheet.getLastColumn();
    var dataRange = sheet.getRange(lastRow, 1, 1, nbColumn);
    var data = dataRange.getValues();  

    // variables to manage the client's datas
    for (i in data){
      var row = data[i];
      var prenom = row[1];
      var nom = row[2];
      var telephone = row[3];
      var email= row[4];
      var statut = row[5];
      var societe = row[6];
      var nbCartons = row[7];
      var nbDisplay = row[8];
      var message = row[9];
    }

    //sign mail LOGO
    var logo = "http://monsite.fr/img/logo.png";

    Logger.log(email);

    MailApp.sendEmail({
      to: email,
      from: "contact@mail.com",
      subject: "Confirmation",
      htmlBody:"<h1 style='color:#006633'>Bonjour "+ prenom +", <br/>ceci est un mail de confirmation.</h1>"
      +"<h3>Merci de l'intéret que vous portez à notre société.</h3>"
      +"<p>Voici le récapitulatif de vos informations personnelles : </p>"
      +"<ul>"
      +"<li>Votre nom : "+ nom +"</li>"
      +"<li>Votre prénom : "+ prenom +"</li>"
      +"<li>Votre numéro de téléphone : "+ telephone +"</li>"
      +"<li>Votre statut : " + statut + "</li>"
      +"<li>Votre société : "+ societe +"</li>"
      +"<li>Vous avez demandé : "+ nbCartons +" carton(s) </li>"
      +"<li>Vous avez demandé : "+ nbDisplay +" display(s) </li>"
      +"<li>Et votre message : "+ message +"</li>"
      +"</ul>"
      +"<p>Nous traitons votre demande au plus vite. Nous vous remercie pour votre confiance.</p>"
      +"<img src="+logo+">"
    });



   // return json success results
    return ContentService
          .createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
          .setMimeType(ContentService.MimeType.JSON);

  } catch(e){
    // if error return this
    return ContentService
          .createTextOutput(JSON.stringify({"result":"error", "error": e}))
          .setMimeType(ContentService.MimeType.JSON);
  } finally { //release lock
    lock.releaseLock();
  }
}

function setup() {
    var doc = SpreadsheetApp.getActiveSpreadsheet();
    SCRIPT_PROP.setProperty("key", doc.getId());
}