How to Create a Web Form that can send emails using your Gmail account
How to Create a Web Form that can send emails using your Gmail account
HTML Send Email via Apps Script?
How to send an email from a HTML form, using Google Apps Script and JavaScript.? Front-end code to send emails from html forms.
Exercise : Create an HTML form with fields for the data that you want to send.? Setup the JavaScript to validate the form input values, and create an object of data to send to the Apps Script endpoint.
HTML CODE
<!DOCTYPE html>
<html>
?<head>
???<title>JavaScript Course</title>
???<style>
???????* {
???????????box-sizing: border-box;
???????}
????????label {
???????????display: block;
???????????font-family: Arial, Helvetica, sans-serif;
???????????font-size: 0.8em;
???????????padding-top: 15px;
???????}
????????.myForm {
???????????width: 90%;
???????????margin: auto;
???????????border: 1px solid #ddd;
???????????padding: 10px;
???????????background-color: #eee;
???????}
????????#myForm input,
???????textarea {
???????????width: 100%;
???????????padding: 10px;
????????}
????????input[type="submit"] {
???????????background-color: black;
???????????color: white;
???????????text-transform: capitalize;
???????????font-size: 1.2em;
???????????border-radius: 10px;
???????}
???</style>
</head>
<body>
???<div class="myForm">
???????<form id="myForm">
???????????<h1>Send Message</h1>
???????????<div>
???????????????<label for="name">Name:</label>
???????????????<input type="text" id="name">
????????????</div>
???????????<div>
???????????????<label for="email">Email:</label>
???????????????<input type="email" id="email">
????????????</div>
???????????<div>
???????????????<label for="message">Message:</label>
???????????????<textarea id="message"></textarea>
????????????</div>
???????????<input type="submit" value="send message">
???????</form>
???</div>
???<script src="app3.js"></script>
</body>
</html>
JavaScript Code
const url = '';
const myForm = document.querySelector('#myForm');
const myName = document.querySelector('#name');
const myEmail = document.querySelector('#email');
const myMessage = document.querySelector('#message');
?myName.value = 'Laurence Svekis';
myEmail.value = 'gapp*****@gmail.com';
myMessage.value = 'Hello World';
myForm.addEventListener('submit', submitter);
?function submitter(e) {
???console.log('submitted');
???e.preventDefault();
???let message = '';
???if (myName.value.length < 5) {
???????myName.style.borderColor = 'red';
???????message += `<br>Name needs to be 5 characters`;
???}
???if (myEmail.value.length < 5) {
???????myEmail.style.borderColor = 'red';
???????message += `<br>Email is missing`;
???}
???if (message) {
???????const div = document.createElement('div');
???????div.innerHTML = message;
???????div.style.color = 'red';
???????myForm.append(div);
???????setTimeout(() => {
???????????div.remove();
???????????myName.style.borderColor = '';
???????????myEmail.style.borderColor = '';
???????}, 5000);
????} else {
???????const myObj = {
???????????name: myName.value,
???????????email: myEmail.value,
???????????message: myMessage.value
???????};
???????console.log(myObj);
???}
}
Send POST request to Google Apps Script
In this lesson the application will be updated to make a fetch request using the POST method to the Google Apps Script endpoint, and insert the form field data into a spreadsheet.
Exercise : Update the fetch method to POST, include the form field data as an object in the POST request body contents.? Create the Google Apps Script endpoint using a webapp to receive the GET and POST request data from the AJAX request from JavaScript.???
Create a web app with Google Apps Script GET method.??
Apps Script Code:
function doGet(e) {
?return ContentService.createTextOutput(JSON.stringify(e)).setMimeType(ContentService.MimeType.JSON);
}
?Google Apps Script Testing adding to sheet data
Apps script code
function tester() {
?const id = '1csURUCONXy*****@M-c0';
?const ss = SpreadsheetApp.openById(id).getSheetByName('emails');
?const sheetdata = ss.getDataRange().getValues();
?const str = '{"name":"Laurence Svekis","email":"gapps*****@.com","message":"Hello World","status":"success"}';
?const json = JSON.parse(str);
?Logger.log(json);
?Logger.log(sheetdata[0]);
?const holder = [];
?sheetdata[0].forEach((heading, index) => {
???if (json[heading]) holder[index] = (json[heading]);
?})
?Logger.log(holder);
?ss.appendRow(holder);
}
Create a web app with Google Apps Script POST method.?
Apps Script
function doPost(e) {
?const id = '1csUR***c0';
?const ss = SpreadsheetApp.openById(id).getSheetByName('emails');
?const sheetdata = ss.getDataRange().getValues();
?const json = JSON.parse(e.postData.contents);
?json.status = 'success';
?const holder = [];
?sheetdata[0].forEach((heading, index) => {
???if (json[heading]) holder[index] = (json[heading]);
?})
?ss.appendRow(holder);
?json.rowval = ss.getLastRow();
?return ContentService.createTextOutput(JSON.stringify(json)).setMimeType(ContentService.MimeType.JSON);
}
JavaScript Code
?const url = 'https://script.google.com/macros/s/AKf***C/exec';
const myForm = document.querySelector('#myForm');
const myName = document.querySelector('#name');
const myEmail = document.querySelector('#email');
const myMessage = document.querySelector('#message');
myName.value = 'Laurence Svekis';
myEmail.value = 'gapps*****@@gmail.com';
myMessage.value = 'Hello World';
myForm.addEventListener('submit', submitter);
?
function submitter(e) {
???console.log('submitted');
???e.preventDefault();
???let message = '';
???if (myName.value.length < 5) {
???????myName.style.borderColor = 'red';
???????message += `<br>Name needs to be 5 characters`;
???}
???if (myEmail.value.length < 5) {
???????myEmail.style.borderColor = 'red';
???????message += `<br>Email is missing`;
???}
???if (message) {
???????const div = document.createElement('div');
???????div.innerHTML = message;
???????div.style.color = 'red';
???????myForm.append(div);
???????setTimeout(() => {
???????????div.remove();
???????????myName.style.borderColor = '';
???????????myEmail.style.borderColor = '';
???????}, 5000);
?
???} else {
???????const myObj = {
???????????name: myName.value,
???????????email: myEmail.value,
???????????message: myMessage.value
???????};
???????addSendMail(myObj);
???}
}
?
function addSendMail(data){
???console.log(data);
???fetch(url,{
???????method:'POST',
???????body:JSON.stringify(data)
???})
???.then(res => res.json())
???.then(json =>{
???????console.log(json);
???})
}
?
function addSendMailGET(data){
???const url1 = url + '?id=100';
???fetch(url1)
???.then(res => res.json())
???.then(json =>{
???????console.log(json);
???})
}
?
Google Apps Script Source Code Complete
function doPost(e) {
?const id = '1csURUCONX****cR7gM-c0';
?const ss = SpreadsheetApp.openById(id).getSheetByName('emails');
?const sheetdata = ss.getDataRange().getValues();
?const json = JSON.parse(e.postData.contents);
?json.status = 'success';
?const holder = [];
?sheetdata[0].forEach((heading, index) => {
???if (json[heading]) holder[index] = (json[heading]);
领英推荐
?})
?ss.appendRow(holder);
?json.rowval = ss.getLastRow();
?return ContentService.createTextOutput(JSON.stringify(json)).setMimeType(ContentService.MimeType.JSON);
}
?
function tester() {
?const id = '1csURUC*****@gM-c0';
?const ss = SpreadsheetApp.openById(id).getSheetByName('emails');
?const sheetdata = ss.getDataRange().getValues();
?const str = '{"name":"Laurence Svekis","email":"gap*****@@gmail.com","message":"Hello World","status":"success"}';
?const json = JSON.parse(str);
?Logger.log(json);
?Logger.log(sheetdata[0]);
?const holder = [];
?sheetdata[0].forEach((heading, index) => {
???if (json[heading]) holder[index] = (json[heading]);
?})
?Logger.log(holder);
?ss.appendRow(holder);
}
?
function doGet(e) {
?return ContentService.createTextOutput(JSON.stringify(e)).setMimeType(ContentService.MimeType.JSON);
}
?
Send Email when the form is submitted
Send an email to your email address with the form content when the web form is submitted.? Send a response confirmation email to the user’s email address from the submitted form content.
Exercise : Update the Google Apps Script to send emails to the user's email address in response to the web form submission, send a second email to your email when the form data is submitted with the form field information.
Create a test function to send emails using data from an object
You should be able to send emails to the user, to yourself and also the data should still be added into the spreadsheet whenever the form is submitted.
function sendMyEmail(data) {
?let emailBody = `<div>Name ${data.name}</div>`;
?emailBody += `<div>Email ${data.email}</div>`;
?emailBody += `<div>Message ${data.message}</div>`;
?MailApp.sendEmail({
???to: 'g*****@@gmail.com',
???subject: 'NEW Web Form Email',
???htmlBody: emailBody
?});
?if (validateEmail(data.email)) {
???let repHTML = `<h2>Thank you ${data.name}</h2>`;
???repHTML += `<div>We will respond shortly. Message received ID ${data.rowval}</div>`;
???MailApp.sendEmail({
?????to: data.email,
?????subject: 'Thank you for your email',
?????htmlBody: repHTML
???});
???return true;
?} else {
???return false;
?}
}
?
function validateEmail(email) {
?const re = /\S+@\S+\.\S+/;
?return re.test(email);
}
?
function testEmail() {
?const val = {
???email: 'gapps*****@gmail.com',
???name: 'tester',
???message: 'Hello World',
???rowval: 50
?}
?Logger.log(sendMyEmail(val));
}
Update JavaScript to manage the submission of the data and provide user feedback
JAVASCRIPT
const url = 'https://script.google.com/macros/s/AKfyc*******XfK2iR/exec';
const myForm = document.querySelector('#myForm');
const myName = document.querySelector('#name');
const myEmail = document.querySelector('#email');
const myMessage = document.querySelector('#message');
const subBtn = document.querySelector('input[type="submit"]');
const main = document.querySelector('.myForm');
myName.value = 'Laurence Svekis';
myEmail.value = 'gapp*******@gmail.com';
myMessage.value = 'Hello World';
myForm.addEventListener('submit', submitter);
?
function submitter(e) {
???console.log('submitted');
???e.preventDefault();
???subBtn.disabled = true;
???let message = '';
???if (myName.value.length < 5) {
???????myName.style.borderColor = 'red';
???????message += `<br>Name needs to be 5 characters`;
???}
???if (myEmail.value.length < 5) {
???????myEmail.style.borderColor = 'red';
???????message += `<br>Email is missing`;
???}
???if (message) {
???????const div = document.createElement('div');
???????div.innerHTML = message;
???????div.style.color = 'red';
???????myForm.append(div);
???????setTimeout(() => {
???????????div.remove();
???????????myName.style.borderColor = '';
???????????myEmail.style.borderColor = '';
???????}, 5000);
???????subBtn.disabled = false;
???} else {
???????const myObj = {
???????????name: myName.value,
???????????email: myEmail.value,
???????????message: myMessage.value
???????};
???????myForm.style.display = 'none';
???????addSendMail(myObj);
???}
}
?
function addSendMail(data){
???console.log(data);
???const repDiv = document.createElement('div');
???repDiv.textContent = 'Waiting.....';
???main.append(repDiv);
???fetch(url,{
???????method:'POST',
???????body:JSON.stringify(data)
???})
???.then(res => res.json())
???.then(json =>{
???????console.log(json);
???????if(json.rowval){
???????????repDiv.textContent = `Message Sent Your ID is ${json.rowval}`;
???????}else{
???????????repDiv.remove();
???????????subBtn.disabled = false;
???????????myForm.style.display = 'block';
???????}
??????
???})
}
?
function addSendMailGET(data){
???const url1 = url + '?id=100';
???fetch(url1)
???.then(res => res.json())
???.then(json =>{
???????console.log(json);
???})
}
?
Google Apps Script
?
function doPost(e) {
?const id = '1csURUCO********';
?const ss = SpreadsheetApp.openById(id).getSheetByName('emails');
?const sheetdata = ss.getDataRange().getValues();
?const json = JSON.parse(e.postData.contents);
?json.status = 'success';
?const holder = [];
?sheetdata[0].forEach((heading, index) => {
???if (json[heading]) holder[index] = (json[heading]);
?})
?ss.appendRow(holder);
?json.rowval = ss.getLastRow();
?json.result = sendMyEmail(json);
?return ContentService.createTextOutput(JSON.stringify(json)).setMimeType(ContentService.MimeType.JSON);
}
?
?
function sendMyEmail(data) {
?let emailBody = `<div>Name ${data.name}</div>`;
?emailBody += `<div>Email ${data.email}</div>`;
?emailBody += `<div>Message ${data.message}</div>`;
?MailApp.sendEmail({
???to: 'gap*****gmail.com',
???subject: 'NEW Web Form Email',
???htmlBody: emailBody
?});
?if (validateEmail(data.email)) {
???let repHTML = `<h2>Thank you ${data.name}</h2>`;
???repHTML += `<div>We will respond shortly. Message received ID ${data.rowval}</div>`;
???MailApp.sendEmail({
?????to: data.email,
?????subject: 'Thank you for your email',
?????htmlBody: repHTML
???});
???return true;
?} else {
???return false;
?}
}
?function validateEmail(email) {
?const re = /\S+@\S+\.\S+/;
?return re.test(email);
}
?function testEmail() {
?const val = {
???email: 'gappsc*****@gmail.com',
???name: 'tester',
???message: 'Hello World',
???rowval: 50
?}
?Logger.log(sendMyEmail(val));
}
?function tester() {
?const id = '1csURU*******gM-c0';
?const ss = SpreadsheetApp.openById(id).getSheetByName('emails');
?const sheetdata = ss.getDataRange().getValues();
?const str = '{"name":"Laurence Svekis","email":"gapp*******@gmail.com","message":"Hello World","status":"success"}';
?const json = JSON.parse(str);
?Logger.log(json);
?Logger.log(sheetdata[0]);
?const holder = [];
?sheetdata[0].forEach((heading, index) => {
???if (json[heading]) holder[index] = (json[heading]);
?})
?Logger.log(holder);
?ss.appendRow(holder);
}
?
function doGet(e) {
?return ContentService.createTextOutput(JSON.stringify(e)).setMimeType(ContentService.MimeType.JSON);
}
?
DUMROS Enterprises
2 年Thanks for this knowledge sharing, Laurence! I'm sure many will have benefitted from your examples, and even with your courses! ??????