auto-reply to a form submission

76 views
Skip to first unread message

Matthew Lake

unread,
Jul 9, 2025, 3:33:36 AM7/9/25
to Google Apps Script Community
Hi

I have a form that i have created, and i have a script that sends an auto-reply with there answers given. This script also sends the answers to 2 different emails. (below is the script). the issue I am having is the formatting. I wanted each question with answer on a separate line but apart from 1 question in the middle they are in a block, I am also unable to change the date style.

Any help would be appriciated.

Regards

Matthew
function onFormSubmit(e) {
  // Open the Visitor Booking-In Form (replace with your actual Form ID)
  var form = FormApp.openById('1B2tvU0AtJ4-waguZuldjibNlE2OT2fCU83jwkqCW6sc');

  // Get the form responses
  var responses = e.response.getItemResponses();


  // Define email bodies
  var emailBody = "Your submission has been received.\n\n" +
                  "Regards,\nMain Reception\n\n" +
                  "Any issues? Please email mainreception as this email box is not monitored.\n\n"
                  "Your submitted details:\n\n";


  var detailsForNotification = "New request below:\n\n";
  var userEmail = "";


  // Process responses
  for (var i = 0; i < responses.length; i++) {
    var question = responses[i].getItem().getTitle();
    var answer = responses[i].getResponse();
   
    emailBody += question + ": " + answer + "\r\n";
    detailsForNotification += question + ": " + answer + "\r\n";
   
    // Capture user email if applicable
    if (question.toLowerCase().includes("email")) {
      userEmail = answer;
    }
  }


  // Send confirmation to visitor if email is found
  if (userEmail) {
    MailApp.sendEmail({
      to: userEmail,
      subject: "Thank you for your request",
      body: emailBody
    });
  } else {
    Logger.log("No email address found in the form submission.");
  }


  // Send notification emails to recipients
  var recipients = ["mainreception@.uk", "carparking@.uk"];
  recipients.forEach(function(email) {
    MailApp.sendEmail({
      to: email,
      subject: "New visitor request",
      body: detailsForNotification
    });
  });
}


// **Setup Trigger Automatically** (Run this manually once)
function createFormSubmitTrigger() {
  var form = FormApp.openById('1B2tvU0AtJ4-waguZuldjibNlE2OT2fCU83jwkqCW6sc');
  ScriptApp.newTrigger("onFormSubmit")
    .forForm(form)
    .onFormSubmit()
    .create();
}





Claude Julien

unread,
Jul 9, 2025, 4:51:20 AM7/9/25
to google-apps-sc...@googlegroups.com
Hello,
I'm not really a programmer, but I'm 100% certain that Gemini 2.5 will do this in less than a minute.
Log in to Google AiStudio to get it for free.
Ask your question and paste your code on the line below, then watch the miracle happen.


Claude
________________________
Look the answer to your question in 20 seconds!
Sometimes it takes several tries.
Just give him an ERROR and tell him again where it's going wrong.

Of course! You're running into two very common and frustrating issues with Google Apps Script: email formatting and date formatting.

  1. The Line Break Issue: The \r\n characters are for plain text emails. Many modern email clients will ignore these and collapse all the text into a single block. The solution is to send the email as HTML, where you can use the <br> tag to force a line break.

  2. The Date Style Issue: When a Google Form has a date or date-time question, Apps Script receives it as a standard JavaScript Date object. When you add this object to a string, it defaults to a very long, technical format (e.g., Fri May 24 2024 09:00:00 GMT+0100 (British Summer Time)). The solution is to detect when an answer is a date and use the Utilities.formatDate() service to style it exactly how you want.

Here is the revised version of your script that fixes both of these issues.

Revised and Corrected Script

Copy and paste this code over your existing onFormSubmit function.

function onFormSubmit(e) {
  // Get the form responses from the event object
  var responses = e.response.getItemResponses();

  // --- Start building the HTML content for the emails ---
  // We use HTML to get proper line breaks and formatting.
  var emailBody = "Your submission has been received.<br><br>" +
                  "Regards,<br>Main Reception<br><br>" +
                  "<i>Any issues? Please email mainreception as this email box is not monitored.</i><br><br>" +
                  "<b>Your submitted details:</b><br><br>";

  var detailsForNotification = "<b>New request below:</b><br><br>";


  var userEmail = "";

  // Process responses
  for (var i = 0; i < responses.length; i++) {
    var question = responses[i].getItem().getTitle();

    var answerObject = responses[i].getResponse();
    var formattedAnswer; // We'll store the final, formatted answer here

    // --- FIX FOR DATE FORMATTING ---
    // Check if the answer is a Date object
    if (answerObject instanceof Date) {
      // It's a date! Let's format it nicely.
      // You can change "dd/MM/yyyy HH:mm" to your desired format.
      // Examples: "dd/MM/yyyy", "d MMMM yyyy", "yyyy-MM-dd"
      formattedAnswer = Utilities.formatDate(answerObject, Session.getScriptTimeZone(), "dd/MM/yyyy HH:mm");
    } else {
      // It's not a date, so use the answer as is.
      formattedAnswer = answerObject;
    }

    // --- FIX FOR LINE BREAKS ---
    // Append the question and formatted answer using HTML <br> tag for a new line.
    emailBody += "<b>" + question + ":</b> " + formattedAnswer + "<br>";
    detailsForNotification += "<b>" + question + ":</b> " + formattedAnswer + "<br>";

    // Capture user email if applicable (this logic remains the same)
    if (question.toLowerCase().includes("email")) {
      userEmail = formattedAnswer;
    }
  }

  // --- Send emails using the 'htmlBody' option ---


 
  // Send confirmation to visitor if email is found
  if (userEmail) {
    MailApp.sendEmail({
      to: userEmail,
      subject: "Thank you for your request",

      htmlBody: emailBody // Use htmlBody instead of body


    });
  } else {
    Logger.log("No email address found in the form submission.");
  }

  // Send notification emails to recipients

  var recipients = ["mainre...@yourdomain.uk", "carpa...@yourdomain.uk"]; // Use your actual domains


  recipients.forEach(function(email) {
    MailApp.sendEmail({
      to: email,
      subject: "New visitor request",

      htmlBody: detailsForNotification // Use htmlBody instead of body
    });
  });
}

// **Setup Trigger Automatically** (Run this manually once from the Script Editor)
// You do not need to run this again if your trigger is already working.


function createFormSubmitTrigger() {
  var form = FormApp.openById('1B2tvU0AtJ4-waguZuldjibNlE2OT2fCU83jwkqCW6sc');

  // Deletes any existing triggers to avoid duplicates
  var triggers = ScriptApp.getProjectTriggers();
  for (var i = 0; i < triggers.length; i++) {
    if (triggers[i].getHandlerFunction() === "onFormSubmit") {
      ScriptApp.deleteTrigger(triggers[i]);
    }
  }
  // Creates a new trigger


  ScriptApp.newTrigger("onFormSubmit")
    .forForm(form)
    .onFormSubmit()
    .create();
}

What Was Changed and Why

  1. Using HTML for Emails:

    • Old: Your email text was being built as a single string with \r\n for new lines.

    • New: The script now builds an HTML string. We replaced \n and \r\n with the HTML line break tag: <br>. I also made the questions bold with <b>...</b> to improve readability.

    • When sending the email, the key change is using the htmlBody option instead of body:

MailApp.sendEmail({
  to: userEmail,
  subject: "Thank you for your request",

  htmlBody: emailBody // <--- THIS IS THE IMPORTANT CHANGE
});

  1. Formatting the Date:

    • Inside the for loop, we now check if the answer from the form is a Date object using instanceof Date.

    • If it is a date, we use Utilities.formatDate(date, timezone, format) to convert it into a clean, readable string.

      • answerObject: The original date from the form.

      • Session.getScriptTimeZone(): This automatically gets the correct timezone from your project settings.

      • "dd/MM/yyyy HH:mm"This is the part you can customize!

        • dd/MM/yyyy would give you 24/05/2024

        • d MMMM yyyy would give you 24 May 2024

        • EEE, d MMM yyyy would give you Fri, 24 May 2024

    • If the answer is not a date (e.g., a name or a phone number), the script uses the answer as it is.

How to Implement

  1. Go to your Apps Script project.

  2. Replace your entire onFormSubmit function with the new code provided above.

  3. Customize the date format string in the Utilities.formatDate() line if you wish.

  4. Save the script project.

Your trigger is likely already set up, so you don't need to run the createFormSubmitTrigger function again. The next time someone submits the form, the emails should be perfectly formatted.



--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/google-apps-script-community/88a4d1dc-adb6-49a5-bb13-b2add7a30cf1n%40googlegroups.com.

George Ghanem

unread,
Jul 9, 2025, 1:30:21 PM7/9/25
to google-apps-sc...@googlegroups.com

Not sure why you are using \r\n. Just use \n\n in the two places in your for loop.

That should do it.


Reply all
Reply to author
Forward
0 new messages