Search code examples
javascriptgoogle-apps-scriptgoogle-sheetsscriptlet

Include a hidden variable in form sent by email - Google Apps Script


I have some script that is sending an HTML form by email as follows:

function sendFormEmail() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheetByName("Email list");
    var emailRange = sheet.getRange("B2:B");
    var emails = emailRange.getValues();
    var lastRow = emails.filter(String).length;
    var originalEmailRange = sheet.getRange("A2:A");

    // Logged emails

    var logSheet = ss.getSheetByName("Email log");
    var timeStampRange = logSheet.getRange("A2:A");
    var timeStamps = timeStampRange.getValues();
    var logEmailRange = logSheet.getRange("B2:B");
    var logEmails = logEmailRange.getValues();
    var lastLog = logEmails.filter(String).length;
    var adjustedLastLog = lastLog+2;
    var userRange = logSheet.getRange("C2:C");
    // Logger.log(adjustedLastLog);


    for(var i=0; i<lastRow; i++) {
    var toEmailAddress = emails[i];
    var htmlMessage = HtmlService.createHtmlOutputFromFile("form.html").getContent();
    var subject = "Connect";
    var message = "";
    logSheet.getRange("B"+(i+adjustedLastLog)).setValue(emails[i]);
    logSheet.getRange("A"+(i+adjustedLastLog)).setValue(new Date());
    logSheet.getRange("C"+(i+adjustedLastLog)).setValue(Session.getActiveUser().getEmail());
    MailApp.sendEmail(toEmailAddress, subject, message, {
      htmlBody: htmlMessage
    });  


    }
    originalEmailRange.setValue("");

    var ui = SpreadsheetApp.getUi();
      var result = ui.alert(
     'Good news!',
     "Your form was successfully sent to your database of emails. Go to the 'Email log' tab to see a log of all emails sent using this function.",
      ui.ButtonSet.OK);

}

What I want to do is somehow parse the active user's email address into a hidden input within the form so that when it is submitted by the user who receives the form, this email is returned with it.

The inputs in the HTML form are pretty basic text inputs such as:

<input type="text"  style="border-radius: 10px; padding: 10px; width: 80%; border: 2px solid #1CA1F2" name="entry.2082149504" value="" class="ss-q-short" id="entry_2082149504" dir="auto" aria-label="And what is this person&#39;s email address?  " title="" style="">

My understanding is that I might need to use Scriptlets but I do not understand the syntax and have tried playing around with it to no avail. Is anyone able to help?

Many thanks


Solution

  • Put a placeholder like {email} in form.html:

    <input type="hidden" name="email" value="{email}">
    

    then replace it with the actual email before sending:

    var htmlMessage = HtmlService.createHtmlOutputFromFile("form.html").getContent();
    htmlMessage = htmlMessage.replace('{email}', toEmailAddress);