To set up a trigger for the function onFormSubmit(e)
which automatically sends an email to a user after they submit a form, you’ll first need to write the function as part of a Google Apps Script project linked to your Google Form or Sheet. Then, you’ll create a trigger that fires every time the form is submitted.
Here’s a step-by-step guide to setting up everything:
1. Write the onFormSubmit
function
You already have the function provided, but here it is embedded within a script file for clarity:
function onFormSubmit(e) {
const itemResponses = e.namedValues;
const email = itemResponses['Email'][0]; // Assumes there's an "Email" column in the form
const name = itemResponses['Name'][0]; // Assumes there's a "Name" column
MailApp.sendEmail({
to: email,
subject: "Thank you for your submission",
body: "Hello " + name + ",\n\nThank you for your submission. We will contact you soon.\n\nBest regards,\nYour Team"
});
}
2. Set up the Trigger in Google Apps Script
To set up the trigger through the Google Apps Script editor:
Using Script Editor:
- Open Google Apps Script: Go to your Google Form or linked Google Sheet, click on Extensions > Apps Script.
- Paste Your Function: If not already added, paste the
onFormSubmit
function into the script editor. - Add Trigger Manually:
- In the Apps Script editor, click on the clock icon on the left-hand panel to go to Triggers.
- Click on “+ Add Trigger” at the bottom right corner.
- Select the
onFormSubmit
function to run. - Choose the event source, which should be either “From spreadsheet” (if you’re using a Google Sheet as a response sheet for the Google Form) or “From form” for direct form responses.
- Set the event type to “On form submit”.
- Adjust other settings such as failure notification settings according to your preference.
- Click “Save”.
Automatically Creating a Trigger via Script:
If you prefer to set up the trigger programmatically, add the following function to your script:
function createFormSubmitTrigger() {
const form = FormApp.openById('YOUR_FORM_ID'); // Replace 'YOUR_FORM_ID' with your actual Google Form ID
ScriptApp.newTrigger('onFormSubmit')
.forForm(form)
.onFormSubmit()
.create();
}
Replace 'YOUR_FORM_ID'
with the actual ID of your Google Form. You can find this ID in the URL when you’re editing the form.
3. Run the createFormSubmitTrigger
Function
After adding the createFormSubmitTrigger
to your script:
- You may need to run
createFormSubmitTrigger
manually from the script editor to create the trigger. - The first time you run it, you will need to authorize the script to interact with your Google Form and send emails on your behalf.
This setup ensures that every time a form is submitted, the onFormSubmit
function is triggered, sending a thank you email to the respondent. Make sure that the form has “Email” and “Name” fields, and they are named exactly as expected by the script.