- Notifications
You must be signed in to change notification settings - Fork910
📧 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) perfect for static websites that need to collect data.
License
dwyl/learn-to-send-email-via-google-script-html-no-server
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Language :English
|한국어 |Español |Português
AStep-by-Step Example of using anHTML Form to send a "Contact Us" Message via Email without a Backend Server using a Google Script - No PHP, Python, Ruby, Java, Node.js etc.
See a working example here:https://dwyl.github.io/learn-to-send-email-via-google-script-html-no-server/
Note: With EU's GDPR, we strongly adviseresearching recommendations on user privacy; you may be heldresponsible for the safekeeping of users' personal data and should provide them a way to contact you.
Warning: Google's API has limits on how many emails it can send in a day.This may vary on your Google account, seethe limits here.We recommend implementing this tutorial through Part 3, since the data willalways be added to the spreadsheet first, then emailed if possible.
We needed a way of sending an email from a "static" HTML pagewhen you don't (want to)have aserver.
- No "Backend" to Deploy/Maintain/Pay for
- Fully Customisable - every aspect is customisable!
- Emailsent viaGoogle Mail which isWhitelisted Everywhere (high deliverability success)
- Collect/Store anyform data in aSpreadsheet for easy viewing(perfect if you need to share it with non-technical people)
Instead of using a server to send your email,which iseasy but requiresmaintenance,use Google to send mail on your behalfand use Google Spreadsheets to keep track of the data!
Youcould use a "free" service likehttps://formspree.io/ to process your form submissionsif you don't care where you are sending your data and want to manage the data submittedin your email inbox (messy ... yuck!)Or... you caninvest a few minutes and keep data private/manageable.Take your pick.
Sample:https://docs.google.com/spreadsheets/d/1Bn4m6iA_Xch1zzhNvo_6CoQWqOAgwwkOWJKC-phHx2Q/copy
Sign in to your Google account and click on "Make a 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.
Open theApps Script editor by clicking "Extensions" > "Apps Script"
Here's asnapshot of the script you need (at this point in the exercise):google-script-just-email.js
Warning: If you do not uncomment and set your email as the value ofTO_ADDRESS
, it is possible for someone who has web skills to alter your formand send emailed data to an arbitrary email address.
This risk may not be very likely. Instead, if you wish, you can leave thisvariable commented out if you accept this possible risk but want the addedconvenience of setting this email variable inside your HTML form as adata-email
attribute. This allows you to easily change where to send emailsinside your HTML form without going back through steps 2-6. This functionalitydoesrequire you to use the provided JS file in Part Two, Step 10.
If you do not want to accept that potential risk, please uncomment the code forthe variableTO_ADDRESS
, and set this value equal to the email which shouldreceive the form's data when submitted.
After making any code changes, you must first save them in the editor using the save icon.
Anyone
option for the 'Who has access' dropdown or form responses will not go through!
Unless youverify your script with Google, you will need to click on "Advanced" and "Go to ... (unsafe)" to give this app permissions.
Copy the web app URL to your clip board / note pad.Then Click "OK".
Using the template inindex.html
in this repo,create your own html file with the basic form. (save the file)
- Each of your form elements must have a
name
attribute equal to that of your column name in the Google sheet - The form's
class
must begform
, i.e.<form>
- If you want to alter this later, you will need to create yourown version of
form-submission-handler.js
and amend the expectedclass
- If you want to alter this later, you will need to create yourown version of
Remember to change the Form
action
URL to the one you copied inthe previous step:
Fill in some sample data in the HTML Form:
Submit the form. You should see a confirmation that it was sent:
Open the inbox for the email address you set inStep 3 (above)
Done. That's it. You just created an HTML form that sends email!
We are going to keep thisSuper Lean by usingPURE CSSfor our Style (fix the "ugly" HTML Form in step 8).Andsubmit
the form usingJQuery "AJAX" to keep the personon your page/site (avoid "ugly" response page)
Toprevent the page from changing to theJSON
response/resultwe need to submit the form usingAJAX.
Downloadthe following Javascript file and update yourindex.html
to point to it at theend of your file(*before the closing</body>
tag)
<scriptdata-cfasync="false"type="text/javascript"src="form-submission-handler.js"></script>
Warning: If you did not set theTO_ADDRESS
variable in Step 3, thenyou need to include adata-email="example@email.net"
attribute inside themain form element. See the example form for more details. Otherwise, if you didset this variable, then you do not need this form attribute.
This keeps the person on the same page. No refresh. Next step is making a thank you message appear.
After following step 10, you can choose to add a thank you message after submitting. Add the following code between the<form>
and</form>
tags:
<divstyle="display:none"class="thankyou_message"><!-- You can customize the thankyou message by editing the code below --><h2><em>Thanks</em> for contacting us! We will get back to you soon!</h2></div>
This will now display a "Thank You"message when the form is submitted:
Tailor your message by editing thethankyou_message
div.
Forthis
example we are usingPure CSS:https://purecss.io/start/because itslight weight (4.0KB minified and gzipped)andsolves our current "problem": Making it Look Good.
Without spendingtoo much time on this, we can make the formlooka lot nicer:
By default, the sent email's body contains the key-value pairs from the form, with the key as an<h4>
and the value as a<div>
. This is a fairly basic, and foolproof view for the data.
You should get something that looks roughly like:
Bear in mind that this is a work in progress and does potentially open you up to getting more than you bargained for in the email. Because the email content is now looping over all the data sent in the form, if a robot or malicious user decides to
POST
more than you've asked for, you'll likely get it in your inbox. Use with caution for now. We're investigating improvements.
You can modify this though, via the script editor. The line:
result+="<h4 style='text-transform: capitalize; margin-bottom: 0'>"+key+"</h4><div>"+obj[key]+"</div>";
has all you need. You can adjust the markup to suit you. We chose an<h4>
because it was the best size for the email, and added the small amount of CSS to it to fix the capitalisation (the keys are all lower case in the JS object) and a bit of default spacing. While inline styles like this are generally bad practice on normal web pages, for email HTML they're about the only reliable way to do CSS!We went with a<div>
for the value part, because it could be anything - single-line, multiline (a<p>
for example wouldn't cut it).
While we're here, there's also areplyTo
option for thesendEmail()
method which is commented out by default:
MailApp.sendEmail({to:TO_ADDRESS,subject:"Contact form submitted",// replyTo: String(mailData.email), // This is optional and reliant on your form actually collecting a field named `email`htmlBody:formatMailBody(mailData)});
You can uncomment that if you want to add a reply-to field to your email. The example in the script will set the reply-to as the email submitted in the form.
Google's documentation provides more information about MailApp.sendEmail (for examplecc
/bcc
etc.) if you're interested:https://developers.google.com/apps-script/reference/mail/mail-app
Sending the form data directly to your email inbox is agoodfirst step, but we can do better. Also, as noted above, Googlehas limits on how many emails you can send in a day, so storingthe data into a spreadsheet is safer and less prone to data loss.
This will record the data received from thePOST
as arow in the spreadsheet.See:google-apps-script.js for the full code you cancopy-paste.
Follow Steps 4, 5 & 6 to save a new version andre-publish the script.
Because we are loading external.js files, our web browserwill notallow us to simply open theindex.html from alocal directory for testing out the form.
Open your terminal and run this commandtoinstall thenode modules andstart thelive server:
npm install live-server --save-dev&& node_modules/.bin/live-server --port=8000
It will take a minute to install,but once that's done yourlive-server
will start up.
That starts a node.js HTTP server on port 8000and opens the form you just created in your default browser.If you wish to update the form styles instyle.css or theclient-side Javascript inform-submission-handler.js,please be sure to editindex.html to load those resourceslocally rather than via GitHub.
Note: This is alight taste of Node.js for absolute beginners.You donot need node.js to "deploy" this form,you can run it on anany web server that serves HTML/CSS/JavaScript.If you have never used Node.js before, see:http://nodeguide.com/beginner.htmlbut for the purposes of this exercise (submitting a formwithout a server)youdon'tneed node.js or
live-server
it's just anice thing to have when you are creatingyour form because it automatically re-loads the page when you make changes in your text editor!
If you want us to take this tutorial further,please let us know!
For your convenience, we have hosted a working demo of the field on GitHubPages, check it out to see the code and how it works:https://dwyl.github.io/learn-to-send-email-via-google-script-html-no-server/
In response toHenry Beary's requestwe made the form handlergeneric which means you can now add any fields you want to the form.
We also created a form,test.html
, which uses all kinds of form input elementsso you can just copy and paste elements as desired into your own form. Just besure to update their names and IDs. You can find a working example of this testform here:https://dwyl.github.io/learn-to-send-email-via-google-script-html-no-server/test.html
Remember to include the fieldsinside the form that has the classgform
and ensure that thename
of the form element matches the new column heading in your spreadsheet.e.g:
<fieldsetclass="pure-group"><labelfor="color">Favourite Color:</label><inputid="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!
This resource may help you get started on uploading files to Google Drive from the Google Script.
- How can I get help using this tutorial?
- Feel free topost an issue describing in detail which steps you have gone through and what isn't working. To get a helpful response, please provide aworking example that reproduces your issue. For example, seethis sample CodePen.
- Can I get edit access to the example spreadsheet?
- No. This is being used to show a working example for anyone to copy, and an editable version could be broken accidentally, or maliciously, by any user.
- Why is the webpage forwarding to a bunch of text when I hit submit?
- You are not properly loading the required Javascript which submits the data via AJAX, or your browser does not support AJAX. Please see Part 2 and check your console logs in case you are finding errors.
- Why is the webpage not successfully submitting the form?
- Check your Javascript console logs. There could be an error while reading in the Javascript we have provided. There could be errors while submitting the form. It is required that your form have a class of
gform
, and also adata-email
attribute if you have not set theTO_ADDRESS
variable inside the Google Script file. Furthermore, the provided Javascript code also expects to see an email form element which it uses to check, a warning message for that element when an improper email is submitted, and then athank-you
div as well, which is shown after a form is successfully submitted. Please ensure that all of these HTML elements are in your form. See the sample file for code you can copy and paste. When you have all of these elements and a proper form set up, you should not see any error messages in your Javascript console when you hit submit.
- The webpage is saying my data was submitted, but why isn't my data being saved or sent to me?
- When you copied the spreadsheet and published the Google Script, did you set the permissions to "Anyone, even Anonymous"? This is required for the form to work, since anyone on the internet can hit send to give you their data. Be sure that you have deployed the proper version of the script and used "Manage versions..." when making changes.
- How do I change the emails this script sends?
- You can tweak the Google Script on the server to send emails to anyone and in whatever format you wish. This could be used to send a confirmation email to those contacting you, but we have not added this feature to this tutorial to avoid potential spamming. The sender of the email will always be the Google account you use to create the form/script, however. Further details on how to customize the email can be found inthe
MailApp
API. You can instead usetheGmailApp
API which may be more flexible for certain use-cases.
- Is this secure? Can I use it for sensitive data?
- No. While data that is sent over POST may be more protected, the information could easily be intercepted by a third party or middleman, and Google has complete access to the data inside a Google Spreadsheet. Email is also not a very secure communication medium by default. We would recommend you invest in a secure platform and server for storing your data if this is a requirement.
- What if my data is sent or stored in the wrong order?
- If your data is in the wrong order, it is recommended to verify that you are loading the clientside JS correctly. The most effective way to do this is to place a
debugger
call inside thehandleFormSubmit()
function, and, if it hits the debugger and opens the respective Dev Tools for the broswer/environment, then the clientside JS is being loaded correctly. If the debugger isn't hit, then the JS isnot either not loaded or not targeting your form, defaulting the data to a plain object which will have its own alphabetic ordering instead.
- 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:https://stackoverflow.com/questions/10000020/ajax-post-to-google-spreadsheet which points to:
About
📧 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) perfect for static websites that need to collect data.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.