learn-to-send-email-via-google-script-html-no-server
: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) perfect for static websites that need to collect data.
Top Related Projects
Responsive transactional HTML email templates
A free simple responsive HTML email template
A few simple, but solid patterns for responsive HTML email templates and newsletters. Even in Outlook and Gmail.
MJML: the only framework that makes responsive-email easy
Rock-solid transactional email templates for applications.
Quick Overview
This GitHub repository provides a step-by-step guide on how to send emails using Google Apps Script and HTML forms without the need for a server. It's designed to be a simple, free solution for sending emails directly from static websites or HTML pages.
Pros
- No server required, reducing costs and complexity
- Uses Google's reliable infrastructure for email sending
- Easy to implement and maintain
- Free for up to 100 emails per day
Cons
- Limited to 100 emails per day on the free tier
- Requires a Google account to set up and use
- May not be suitable for high-volume email sending
- Dependent on Google's services and policies
Code Examples
- HTML form example:
<form id="gform" method="POST" action="https://script.google.com/macros/s/YOUR_SCRIPT_ID/exec">
<input type="text" name="name" placeholder="Name" required>
<input type="email" name="email" placeholder="Email" required>
<textarea name="message" placeholder="Message" required></textarea>
<button type="submit">Send</button>
</form>
- Google Apps Script code snippet:
function doPost(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var result = {};
result.parameters = e.parameter;
result.contentLength = e.postData.contents.length;
result.postData = e.postData.contents;
sheet.getRange(sheet.getLastRow() + 1, 1, 1, 1).setValue(JSON.stringify(result));
return ContentService.createTextOutput(JSON.stringify(result)).setMimeType(ContentService.MimeType.JSON);
}
- JavaScript for form submission:
$("#gform").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(),
success: function(data) {
console.log(data);
$('#gform *').fadeOut(2000);
$('#gform').prepend('Your submission was successful.');
}
});
});
Getting Started
- Create a new Google Sheet and Google Apps Script project.
- Copy the provided Google Apps Script code into your project.
- Deploy the script as a web app and copy the URL.
- Create an HTML form and set the form action to your script URL.
- Customize the form fields and styling as needed.
- Test the form submission and verify that emails are being sent.
For detailed instructions and troubleshooting, refer to the repository's README.md file.
Competitor Comparisons
Responsive transactional HTML email templates
Pros of transactional-email-templates
- Provides a comprehensive set of pre-designed email templates for various use cases
- Templates are responsive and tested across different email clients
- Offers both HTML and plain text versions of templates
Cons of transactional-email-templates
- Requires integration with Mailgun or another email service provider
- May have a steeper learning curve for beginners
- Limited customization options without advanced HTML/CSS knowledge
Code Comparison
learn-to-send-email-via-google-script-html-no-server:
<form id="gform" method="POST" action="https://script.google.com/macros/s/...">
<input type="text" name="name" placeholder="Name" required>
<input type="email" name="email" placeholder="Email" required>
<button type="submit">Send</button>
</form>
transactional-email-templates:
<table class="body-wrap" bgcolor="#f6f6f6">
<tr>
<td class="container" bgcolor="#FFFFFF">
<div class="content">
<h1>Welcome, {{name}}!</h1>
<p>Thanks for signing up. We're thrilled to have you on board.</p>
</div>
</td>
</tr>
</table>
The learn-to-send-email-via-google-script-html-no-server project focuses on a simple form submission using Google Scripts, while transactional-email-templates provides more complex, pre-designed email templates. The former is easier for beginners but less feature-rich, while the latter offers more professional-looking templates but requires more setup and integration with an email service provider.
A free simple responsive HTML email template
Pros of responsive-html-email-template
- Focuses on responsive design, ensuring emails look good across devices
- Provides a clean, modern template as a starting point for email designs
- Includes extensive comments explaining each section of the template
Cons of responsive-html-email-template
- Doesn't include a method for sending emails, only provides the template
- Less comprehensive documentation compared to learn-to-send-email-via-google-script-html-no-server
- Lacks integration with Google Sheets for data management
Code Comparison
learn-to-send-email-via-google-script-html-no-server:
function doPost(e) {
var mailData = e.parameters;
sendEmail(mailData);
return ContentService.createTextOutput("Email sent successfully!");
}
responsive-html-email-template:
<table role="presentation" border="0" cellpadding="0" cellspacing="0" class="body">
<tr>
<td> </td>
<td class="container">
<div class="content">
<!-- START CENTERED WHITE CONTAINER -->
The code snippets highlight the different focus of each project. learn-to-send-email-via-google-script-html-no-server emphasizes the email sending functionality using Google Scripts, while responsive-html-email-template concentrates on the HTML structure for responsive email design.
A few simple, but solid patterns for responsive HTML email templates and newsletters. Even in Outlook and Gmail.
Pros of Cerberus
- Focuses on creating responsive HTML email templates
- Provides a set of modular, customizable email patterns
- Extensively tested across various email clients and devices
Cons of Cerberus
- Requires more technical knowledge to implement and customize
- Limited to email template creation, not a complete email sending solution
- May require additional tools or services for actual email delivery
Code Comparison
Cerberus (HTML email template):
<table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%">
<tr>
<td style="padding: 20px 0 30px 0;">
<table align="center" cellspacing="0" cellpadding="0" border="0" width="600" style="border-collapse: collapse;">
<!-- Email content goes here -->
</table>
</td>
</tr>
</table>
learn-to-send-email-via-google-script-html-no-server (Google Apps Script):
function doPost(e) {
try {
MailApp.sendEmail({
to: e.parameter.email,
subject: "Contact form submitted",
htmlBody: formatMailBody(e.parameters)
});
return ContentService.createTextOutput("Success!");
} catch(error) {
return ContentService.createTextOutput("Error: " + error.message);
}
}
The code snippets highlight the different focus of each project: Cerberus provides HTML structure for email templates, while learn-to-send-email-via-google-script-html-no-server offers a serverless email sending solution using Google Apps Script.
MJML: the only framework that makes responsive-email easy
Pros of mjml
- Provides a responsive email framework for creating visually appealing emails
- Offers a wide range of pre-built components for easy email design
- Supports multiple rendering engines and email clients
Cons of mjml
- Requires learning a specific syntax and framework
- May have a steeper learning curve for beginners
- Limited to email design and doesn't handle sending functionality
Code Comparison
learn-to-send-email-via-google-script-html-no-server:
<form id="gform" method="POST" action="https://script.google.com/macros/s/...">
<input type="text" name="name" placeholder="Name" required>
<input type="email" name="email" placeholder="Email" required>
<button type="submit">Send</button>
</form>
mjml:
<mjml>
<mj-body>
<mj-section>
<mj-column>
<mj-text>Hello World</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml>
Summary
learn-to-send-email-via-google-script-html-no-server focuses on sending emails using Google Scripts without a server, while mjml is a framework for designing responsive emails. The former is simpler to use for basic email sending, while the latter offers more advanced design capabilities but requires learning its specific syntax.
Rock-solid transactional email templates for applications.
Pros of postmark-templates
- Provides a comprehensive set of responsive email templates for various use cases
- Templates are thoroughly tested across different email clients for compatibility
- Includes both HTML and plain text versions of templates
Cons of postmark-templates
- Requires integration with Postmark or other email service providers
- Less flexibility for customization compared to building emails from scratch
- May have a steeper learning curve for beginners
Code Comparison
postmark-templates:
<table class="email-content" width="100%" cellpadding="0" cellspacing="0" role="presentation">
<tr>
<td class="email-body" width="100%" cellpadding="0" cellspacing="0">
<table class="email-body_inner" align="center" width="570" cellpadding="0" cellspacing="0" role="presentation">
<!-- Email Body Content -->
</table>
</td>
</tr>
</table>
learn-to-send-email-via-google-script-html-no-server:
<form id="gform" method="POST" class="pure-form pure-form-stacked" data-email="example@email.net"
action="https://script.google.com/macros/s/...../exec">
<!-- Form fields -->
<button class="button-success pure-button button-xlarge">
<i class="fa fa-paper-plane"></i> Send
</button>
</form>
The postmark-templates repository focuses on providing ready-to-use email templates, while learn-to-send-email-via-google-script-html-no-server emphasizes a serverless approach using Google Scripts for sending emails directly from HTML forms.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Send Email from a Static HTML Form using Google Apps Mail!
Language : English
| íêµì´ | Español | Português
A Step-by-Step Example of using an HTML 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 advise researching recommendations on user privacy; you may be held responsible 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, see the limits here. We recommend implementing this tutorial through Part 3, since the data will always be added to the spreadsheet first, then emailed if possible.
Why?
We needed a way of sending an email from a "static" HTML page when you don't (want to) have a server.
Key Advantages
- No "Backend" 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 https://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/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.
2. Open the Script Editor
Open the Apps Script editor by clicking "Extensions" > "Apps Script"
Here's a snapshot of the script you need (at this point in the exercise): google-script-just-email.js
3. Set the TO_ADDRESS
in the Script
Warning: If you do not uncomment and set your email as the value of
TO_ADDRESS
, it is possible for someone who has web skills to alter your form
and send emailed data to an arbitrary email address.
This risk may not be very likely. Instead, if you wish, you can leave this
variable commented out if you accept this possible risk but want the added
convenience of setting this email variable inside your HTML form as a
data-email
attribute. This allows you to easily change where to send emails
inside your HTML form without going back through steps 2-6. This functionality
does require 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 for
the variable TO_ADDRESS
, and set this value equal to the email which should
receive the form's data when submitted.
4. Save changes to your Script
After making any code changes, you must first save them in the editor using the save icon.
5. Publish the Updated Script as a Web App
:warning: Note: You must select the Anyone
option for the 'Who has access' dropdown or form responses will not go through! :warning:
6. Authorize the Script to Send Emails
Unless you verify 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".
7. Create your basic HTML Form
Using the template in index.html
in this repo,
create your own html file with the basic form. (save the file)
:warning: If you're already trying to use your own form by this step rather than the example one in this repo:
- 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 class="gform">
- If you want to alter this later, you will need to create your
own version of
form-submission-handler.js
and amend the expectedclass
- If you want to alter this later, you will need to create your
own version of
Remember to change the Form
action
URL to the one you copied in the previous step:
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 JQuery "AJAX" to keep the person
on your page/site (avoid "ugly" response page)
10. Submit the Form using JavaScript "AJAX"
To prevent the page from changing to the JSON
response/result
we need to submit the form using AJAX.
Download the following Javascript file and update your index.html
to point to it at the end of your file
(*before the closing </body>
tag)
<script data-cfasync="false" type="text/javascript" src="form-submission-handler.js"></script>
Warning: If you did not set the TO_ADDRESS
variable in Step 3, then
you need to include a data-email="example@email.net"
attribute inside the
main form element. See the example form for more details. Otherwise, if you did
set 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.
11. Add a customised Thank You Message Shown when Form Submitted
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:
<div style="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 the thankyou_message
div.
12. Use CSS to Make the Form Look Good
For this
example we are using Pure CSS: https://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:
13. Make the email look good too!
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 a replyTo
option for the sendEmail()
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 example cc
/bcc
etc.) if you're interested:
https://developers.google.com/apps-script/reference/mail/mail-app
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. Also, as noted above, Google has limits on how many emails you can send in a day, so storing the data into a spreadsheet is safer and less prone to data loss.
14. Add the record_data
Function to your Google Apps Script
This will record the data received from the POST
as a row in the spreadsheet.
See: google-apps-script.js for the full code you can copy-paste.
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
Live Server (on your localhost
)
Because we are loading external .js files, our web browser will not allow us to simply open the index.html from a local directory for testing out the form.
Open your terminal and run this command to install the node modules and start the live 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 your live-server
will start up.
That starts a node.js HTTP server on port 8000 and opens the form you just created in your default browser. If you wish to update the form styles in style.css or the client-side Javascript in form-submission-handler.js, please be sure to edit index.html to load those resources locally rather than via GitHub.
Note: This is a light taste of Node.js for absolute beginners. You do not need node.js to "deploy" this form, you can run it on an any web server that serves HTML/CSS/JavaScript. If you have never used Node.js before, see: http://nodeguide.com/beginner.html but for the purposes of this exercise (submitting a form without a server) you don't need node.js or
live-server
it's just a nice thing to have when you are creating your form because it automatically re-loads the page when you make changes in your text editor!
Want more?
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 GitHub Pages, 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/
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.
We also created a form, test.html
, which uses all kinds of form input elements
so you can just copy and paste elements as desired into your own form. Just be
sure to update their names and IDs. You can find a working example of this test
form here:
https://dwyl.github.io/learn-to-send-email-via-google-script-html-no-server/test.html
Remember to include the fields inside the form that has the class 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!
Uploading Files
This resource may help you get started on uploading files to Google Drive from the Google Script.
Frequently Asked Questions (FAQ's)
- How can I get help using this tutorial?
- Feel free to post an issue describing in detail which steps you have gone through and what isn't working. To get a helpful response, please provide a working example that reproduces your issue. For example, see this 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 in the
MailApp
API. You can instead use theGmailApp
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 is not either not loaded or not targeting your form, defaulting the data to a plain object which will have its own alphabetic ordering instead.
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: https://stackoverflow.com/questions/10000020/ajax-post-to-google-spreadsheet which points to:
Top Related Projects
Responsive transactional HTML email templates
A free simple responsive HTML email template
A few simple, but solid patterns for responsive HTML email templates and newsletters. Even in Outlook and Gmail.
MJML: the only framework that makes responsive-email easy
Rock-solid transactional email templates for applications.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot