Check out Google Apps Script. Click "Start scripting", and it should bring you to a google-docs-esque text editor.
The gist of it is: You implement either a function doGet(e)
or a function doPost(e)
.
This function will be run when an HTTP request hits the google script's URL.
What this means:
- Your form will do a POST to
https://script.google.com/macros/s/[some_id]/exec
- This will run the
doPost(e)
function, and you can access the form data usinge.parameters
- Whatever the function returns, will be returned to the browser
function doPost(e) {
return ContentService.createTextOutput('Hello, world!');
}
- Copy and paste the above into the
Code.gs
file that should be open in google scripts. - Give the project a name - call it "Emailer" or something
- Click "Publish" => "Deploy as web app"
- Set "Execute the app as" to yourself
- Set the permissions to "Anyone, even anonymous"
- Click "Deploy"
It should now show a link like https://script.google.com/macros/s/[some_id]/exec
,
which you will use as the action
in your form!
So make a form like:
<form action="https://script.google.com/macros/s/[some_id]/exec" method="POST">
<input type="submit" value="Go"></input>
</form>
It should bring you to a page that says "Hello, World".
Google script code:
function doPost(e) {
var name = e.parameters.name;
return HtmlService.createHtmlOutput("<h1>Hello, " + name + ".</h1>");
}
Remember to re-publish your script! "Publish"->"Deploy as web app", and note that it (might?/will?) give you a different URL
Your HTML Form:
<form action=[the url to this script] method="POST">
<input type="text" name="name" placeholder="Enter your name..." />
<input type="submit" value="Submit" />
</form>
When you click submit, it should bring you to a page that says "Hello, ", where is the value you entered in the form.
Try the following code (make sure to substitute with your actual email)
function doPost(e) {
GmailApp.sendEmail("<your email>", "Test email", "test");
return HtmlService.createHtmlOutput("Email sent.");
}
Again, re-publish it as a web app. This should ask you to "Review permissions", where you will give the script the ability to use the Gmail API (ie. read, send, delete email on your behalf).
Update the form's action
if the URL of the script changed from re-publishing,
and this should send you an email when the form is submitted.
I think this covers everything needed to have a contact form that sends you an email with the content from it.
Check out the HtmlService documentation.
You'll probably want to make it a page that says something like
Your contact form has been submitted. Redirecting you back to my site
, and use a meta refresh redirect to bring them back.
Alternatively, you could look into Ajax and jQuery, and then you can do this without them leaving your page.
Warning: lots of javascript