html-form-send-email-via-google-script-without-server
html-form-send-email-via-google-script-without-server copied to clipboard
:email: An Example of using an HTML form (e.g: "Contact Us" on a website) to send Email without a Backend Server (using a Google Script)
Send Email from a custom HTML Form using Google Apps Script!!
A Step-by-Step Example of using an HTML Form to send a "Contact Us" Message via Email using a Google Script - Free tool - No hosting, PHP, Python, Ruby, Java, Node.js etc.
This tutorial has been forked from an existing tutorial by @dwyl & team with contributions by Sean McKenna. Thanks for sharing!
Important: This solution publishes a form as a Google Apps Script Webapp. Webapps currently cannot be embedded in other webpages other than on Google Sites.
Update: There is an undocumented option to permit Webapps to be embedded as
<iframe>
by usingsetXFrameOptionsMode()
. To use uncomment.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
in script.gs.
Why?
We needed a way of sending an email from from a "static" HTML page when you don't have a web hosting server.
Key Advantages
- No web hosting to Deploy/Maintain/Pay for
- Fully Customisable - every aspect is customisable!
- Email sent via Google Mail which is Whitelisted Everywhere (high deliverability success)
-
Collect/Store any form data in a Spreadsheet for easy viewing
(perfect if you need to share it with non-technical people)
What?
Instead of using a server to send your email,
which is easy but requires maintenance,
use Google to send mail on your behalf
and use Google Spreadsheets to keep track of the data!
You could use a "free" service like http://formspree.io/ to process your form submissions if you don't care where you are sending your data and want to manage the data submitted
in your email inbox (messy ... yuck!)
Or... you can invest a few minutes and keep data private/manageable. Take your pick.
How?
1. Make a Copy of the Sample Spreadsheet
Sample: https://docs.google.com/spreadsheets/d/1Kbd8CXZk-hCkdEXsQE70t7AnKYZ-uiLrOaZHrx8gZcE/copy
This should give you something like this:
Note: Feel free to change the name of the Copy to anything you want, it will not affect the outcome.
2. Open the Script Editor
Open the Script editor... by clicking "Tools" > "Script editor..."
Here's a snapshot of the script you need (at this point in the exercise): script.gs
3. Set the TO_ADDRESS
in the Script
In the editor window you should expect to see:
Change the value of the TO_ADDRESS
to which ever email you want to receive
the contact form message.
4. Create your basic HTML Form
Using the template in index.html
in the Script Editor,
create your own html file with the basic form. (save the file)
5. Save a New Version of your Script
It's not immediately obvious but you have to click on "Manage Versions..."
Then create your new version:
6. Publish the Updated Script as a Web App
Select the latest project version to deploy:
7. Authorize the Script to Send Emails
Open the Current web app url into a new browser tab. Then Click "OK".
8. Open the HTML Form (page) in your Browser
Fill in some sample data in the HTML Form:
Submit the form. You should see a confirmation that it was sent:
9. Check the email inbox for the address you set
Open the inbox for the email address you set in Step 3 (above)
Done. That's it. You just created an HTML form that sends email!
Part Two - Make It Look Good ...
We are going to keep this Super Lean by using PURE CSS
for our Style (fix the "ugly" HTML Form in step 8).
And submit
the form using Google Apps Script Client-to-Server Communication to keep the person
on your page/site (avoid "ugly" response page)
10. Submit the Form using Google Apps Script "Client-to-Server Communication"
To prevent the page from changing when submitted the index.html file includes a preventFormSubmit
function.
Update your index.html
to include the following JavaScript file in the <head>
of your file
<script>
// from https://developers.google.com/apps-script/guides/html/communication#forms
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function handleFormSubmit(formObject) {
google.script.run.withSuccessHandler(displayResult).record_data(formObject);
}
function displayResult(e) {
console.log(e);
document.getElementById('thankyou_message').style.display = 'block';
document.getElementById('gform').style.display = 'none';
}
<script>
Now when the form is submitted the form data is sent to our record_data()
function in the script.gs
file. When it finishes the displayResult()
hides the form and will now display a "Thank You" message when the form is submitted:
Keeps the person on the same page. No refresh.
11. Customise the Message Shown when Form Submitted
Taylor your message by editing the thankyou_message
div:
12. Use CSS to Make the Form Look Good
For this
example we are using Pure CSS: http://purecss.io/start/
because its light weight (4.0KB minified and gzipped)
and solves our current "problem": Making it Look Good.
Without spending too much time on this, we can make the form look a lot nicer:
Part Three - Store Submitted Contact Form Data in a Spreadsheet
Sending the form data directly to your email inbox is a good first step, but we can do better.
13. Add the record_data
Function to your Google Apps Script
This will record the data received from the form submission as a row in the spreadsheet.
See: script.gs for the full code you can copy-paste.
14. Run the Setup Script
The Setup Script gets the Name of your associated Google Spreadsheet so it knows where to put the data...
15. Save a New Version and Re-Publish it
Follow Steps 4, 5 & 6 to save a new version and re-publish the script.
16. Re-Test Submitting the Form
17 Confirm the Data was Inserted into the Spreadsheet
Add your own fields!
In response to Henry Beary's request we made the form handler generic which means you can now add any fields you want to the form.
remember to include the fields inside the form that has the id gform
and ensure that the name
of the form element matches the new column heading in your spreadsheet.
e.g:
<fieldset class="pure-group">
<label for="color">Favourite Color: </label>
<input id="color" name="color" placeholder="green" />
</fieldset>
This will allow you to capture the person's favourite color:
e.g:
Let us know if you have any questions!
Background Reading
- Google Apps Scripts Basics: https://developers.google.com/apps-script/articles
- Logger (like console.log): https://developers.google.com/apps-script/reference/base/logger
- Simple Mail Merge using Google Spreadsheets: https://developers.google.com/apps-script/articles/mail_merge
- Original Tutorial: AJAX post to google spreadsheet: http://stackoverflow.com/questions/10000020/ajax-post-to-google-spreadsheet which points to:
- https://mashe.hawksey.info/2011/10/google-spreadsheets-as-a-database-insert-with-apps-script-form-postget-submit-method/