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 application script

how to send email from 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 you want to submit. configure the javascript to validate form input values ​​and create a data object to send to the applications script endpoint.

  1. add html input fields so the user can enter information. apply css styling as needed to style your form fields
  2. using javascript, select input fields as javascript variables
  3. create an event that invokes a function called submitter( ) when the form’s submit button is clicked
  4. using e.preventdefault(); to avoid the default action of the form submit to prepare for ajax.
  5. add conditions on the input field values, set a variable to add content if errors are detected.
  6. if errors are caught in the conditions, print them in a new element that is created with javascript.
  7. set a timeout to remove the error element and reset the input field’s border colors to their default value.
  8. create an object that contains all the input data of the form with property names that match the data.

html code

<!doctype html>

<html>

<head>

<title>javascript course</title>

<style>

* {

box size: border box;

tag {

show: block;

font family: arial, helvetica, sans-serif;

font size: 0.8em;

top padding: 15px;

.myform {

width: 90%;

margin: auto;

border: 1px solid #ddd;

padding: 10px;

background color: #eee;

#myform input,

text area {

width: 100%;

padding: 10px;

input[type=”send”] {

background color: black;

color: white;

text transform: uppercase;

font size: 1.2em;

border-radius: 10px;

</style>

</head>

<body>

<div class=”myform”>

<form id=”myform”>

<h1>send message</h1>

<div>

<tag for=”name”>name:</tag>

<input type=”text” id=”name”>

</div>

<div>

<tag for=”email”>email:</tag>

<input type=”email” id=”email”>

</div>

<div>

<tag for=”message”>message:</tag>

<textarea id=”message”></textarea>

</div>

<input type=”send” value=”send message”>

</form>

</div>

<script src=”app3.js”></script>

</body>

</html>

javascript code

constant 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’;

mymail.value = ‘gapp*****@gmail.com’;

mymessage.value = ‘hello world’;

myform.addeventlistener(‘send’, sender);

function sender(e) {

console.log(‘submitted’);

e.preventdefault();

leave message = ”;

if (myname.value.length < 5) {

myname.style.bordercolor = ‘red’;

message += `<br>name must be 5 characters long`;

if (mymail.value.length < 5) {

mymail.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);

set timeout (() = > {

div.remove();

myname.style.bordercolor = ”;

myemail.style.bordercolor = ”;

}, 5000);

} more {

const myobj = {

name: myname.value,

email: myemail.value,

message: mymessage.value

};

console.log(myobj);

}

send a publish request to the google apps script

In this lesson, the app will update to make a get request using the post method on the google apps script endpoint and insert the data from the form field into a spreadsheet.

Exercise: Update the find method to post, include the form field data as an object in the post request body content. Create the google apps script endpoint using a web application to receive the get and post request data from the javascript ajax request.

Create a web application using the google apps script get method.

  1. go to https://script.google.com/ create a new project
  2. using the doget(e) method create a new function that will return the e parameters from the url request object.
  3. creates and returns the e parameters as a string value. return contentservice.createtextoutput(json.stringify(e))
  4. set the mime type to json setmimetype(contentservice.mimetype.json)
  5. deploy a new web application set the configuration so that run as your account and who has access to anyone
  6. copy the web app url into the javascript app as the search endpoint url.
  7. try sending the request lookup to the google apps script web application and check the response data in the console.
See Also:  Ireland Baldwin reflects on dad Alecs 'thoughtless little pig' voicemail from 15 years ago

application script code:

function doget(e) {

returns contentservice.createtextoutput(json.stringify(e)).setmimetype(contentservice.mimetype.json);

}

google apps script test adding data to sheet

  1. create a new spreadsheet, add in the first row the input field names of the html form
  2. get the spreadsheet id from its url and copy it as id in the google apps script.
  3. create a function called tester() to test the values ​​input to the sheet. dopost() is much more difficult to fix, so best practice is to make the functionality work first, then add it to the dopost() method.
  4. inside the test function, open the sheet, spreadsheetapp.openbyid(id) .getsheetbyname(’emails’) set to a variable
  5. gets the data from the spreadsheet, selecting the first row of header information as an array. ss.getdatarange().getvalues()[0]
  6. create an object that can be used for testing with the same property names as the headers on the sheet and the names of the input fields in the javascript object.
  7. loop through the header names, if there is a value inside the data object, add that header using the index value to a temporary holding array.
  8. using appendrow add the withholding data to the sheet.
  9. try and run the test application to add a new row of data to the spreadsheet columns.

application 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(datasheet[0]);

const holder = [];

sheetdata[0].foreach((header, index) => {

if (json[header]) headline[index] = (json[header]);

})

logger.log(holder);

ss.appendrow(header);

}

Create a web application using the google apps script publish method.

  1. create a new function named dopost(e)
  2. add the test function code in dopost()
  3. using json.parse convert the file sent parameter e contains data as a usable javascript object. json.parse(e.postdata.contents)
  4. get the last row of data using the getlastrow() method and add it to the post data content object.
  5. return the response to data.
  6. deploy a web application, you can use managed implementations to use the existing url or create a new one and update the url in your javascript code.
  7. in code javascript update the ajax request to the new web application url endpoint.
  8. send the fetch request as a post with the input field data body as a string value.
  9. test the code and update the input field values ​​to verify the results in the google sheet rows.

application script

dopost(e) function {

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((header, index) => {

if (json[header]) headline[index] = (json[header]);

})

ss.appendrow(header);

json.rowval = ss.getlastrow();

returns 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’;

mymail.value = ‘gapps*****@@gmail.com’;

mymessage.value = ‘hello world’;

myform.addeventlistener(‘send’, sender);

function sender(e) {

console.log(‘submitted’);

e.preventdefault();

leave message = ”;

if (myname.value.length < 5) {

myname.style.bordercolor = ‘red’;

message += `<br>name must be 5 characters long`;

if (mymail.value.length < 5) {

mymail.style.bordercolor = ‘red’;

message += `<br>email is missing`;

if (message) {

const div = document.createelement(‘div’);

See Also:  Cách tạo và sử dụng Google Group làm việc nhóm hiệu quả, dễ dàng nhất

div.innerhtml = message;

div.style.color = ‘red’;

myform.append(div);

set timeout (() = > {

div.remove();

myname.style.bordercolor = ”;

myemail.style.bordercolor = ”;

}, 5000);

} more {

const myobj = {

name: myname.value,

email: myemail.value,

message: mymessage.value

};

add sendmail(myobj);

}

function addsendmail(data){

console.log(data);

search (url,{

method:’publish’,

body:json.stringify(data)

})

.then(res => res.json())

.then(json =>{

console.log(json);

})

}

function addsendmailget(data){

const url1 = url + ‘?id=100’;

find (url1)

.then(res => res.json())

.then(json =>{

console.log(json);

})

}

full google apps script source code

dopost(e) function {

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((header, index) => {

if (json[header]) headline[index] = (json[header]);

})

ss.appendrow(header);

json.rowval = ss.getlastrow();

returns 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(datasheet[0]);

const holder = [];

sheetdata[0].foreach((header, index) => {

if (json[header]) headline[index] = (json[header]);

})

logger.log(holder);

ss.appendrow(header);

}

function doget(e) {

returns contentservice.createtextoutput(json.stringify(e)).setmimetype(contentservice.mimetype.json);

}

send email when 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 their email when the form data is submitted with the form field information.

create a test function to send emails using data from an object

  1. create a function called sendmyemail that will handle sending emails using an object as the data source.
  2. create a function to validate an email address before trying to send an email email to that user. this should be included to avoid errors in the google apps script that would lead to a cors issue in the web form.
  3. create a test function with mock object data that would come from the form . include the row value that is set from the sheet row that was inserted.
  4. using the mailapp service, use the sendemail method to send an email, with a parameters object to the method . set the to, subject, and htmlbody to the desired values ​​for the email. you should use the form data structure for the object, to simulate the form submit.
  5. check if the email provided by the user is valid, if you are using the submit email, send a response personalized to the user.
  6. using the test data ensures that you can send the email and accept permissions for the app to use the mail app service. this is required, otherwise the application will not be able to send emails.
  7. move the send email function to the dopost() method, using the actual data sent.
  8. deploy the webapp to the endpoint, if you create a new webapp make sure to copy the new url into the webapp.

You need to be able to send emails to the user, to yourself and also the data needs to be added to the spreadsheet each time the form is submitted.

function sendmymail(data) {

let emailbody = `<div>name ${data.name}</div>`;

email body += `<div>email ${data.email}</div>`;

email body += `<div>message ${data.message}</div>`;

mailapp.sendmail({

to: ‘g*****@@gmail.com’,

subject: ‘new webform email’,

htmlbody: email body

});

if (validate email (data. email)) {

let rephtml = `<h2>thanks ${data.name}</h2>`;

rephtml += `<div>we will get back to you shortly. received message id ${data.rowval}</div>`;

See Also:  How to Create and Print Labels in Word Using Mail Merge and Excel Source Data

mailapp.sendmail({

to: data.email,

subject: ‘thank you for your email’,

htmlbody: rephtml

});

returns true;

} more {

returns false;

}

function validate email (email) {

const re = /s+@s+.s+/;

returns re.test(email);

}

testemail() function {

constant value = {

email: ‘gapps*****@gmail.com’,

name: ‘tester’,

message: ‘hello world’,

row value: 50

logger.log(sendmymail(val));

}

update javascript to manage data submission and provide user feedback

  1. when the form is submitted, disable the submit button to avoid a second submission. if there are errors in the form fields, enable the button
  2. if the form fields were completed successfully, hide the form element.
  3. in the addedendmail() function create a new item, add it to the main content area. add text for the user to see that your form was submitted.
  4. once a successful response is returned, update the text in the new field with the id or row value of the imputed content in the sheet . if there was no successful response, display the form for a second data submission.
  5. make adjustments to the handling of the submission process to keep the user informed of the ajax information being submitted and the stage of the data. results of sending the data.

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”]’);

main const = document.queryselector(‘.myform’);

myname.value = ‘laurence svekis’;

mymail.value = ‘gapp*******@gmail.com’;

mymessage.value = ‘hello world’;

myform.addeventlistener(‘send’, sender);

function sender(e) {

console.log(‘submitted’);

e.preventdefault();

subbtn.disabled = true;

leave message = ”;

if (myname.value.length < 5) {

myname.style.bordercolor = ‘red’;

message += `<br>name must be 5 characters long`;

if (mymail.value.length < 5) {

mymail.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);

set timeout (() = > {

div.remove();

myname.style.bordercolor = ”;

myemail.style.bordercolor = ”;

}, 5000);

subbtn.disabled = false;

} more {

const myobj = {

name: myname.value,

email: myemail.value,

message: mymessage.value

};

myform.style.display = ‘none’;

add sendmail(myobj);

}

function addsendmail(data){

console.log(data);

const repdiv = document.createelement(‘div’);

repdiv.textcontent = ‘waiting…..’;

main.append(repdiv);

search (url,{

method:’publish’,

body:json.stringify(data)

})

.then(res => res.json())

.then(json =>{

console.log(json);

if(json.rowval){

repdiv.textcontent = `message sent its id is ${json.rowval}`;

}more{

repdiv.remove();

subbtn.disabled = false;

myform.style.display = ‘lock’;

})

}

function addsendmailget(data){

const url1 = url + ‘?id=100’;

find (url1)

.then(res => res.json())

.then(json =>{

console.log(json);

})

}

google apps script

dopost(e) function {

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((header, index) => {

if (json[header]) headline[index] = (json[header]);

})

ss.appendrow(header);

json.rowval = ss.getlastrow();

json.result = sendmymail(json);

returns contentservice.createtextoutput(json.stringify(json)).setmimetype(contentservice.mimetype.json);

}

function sendmymail(data) {

let emailbody = `<div>name ${data.name}</div>`;

email body += `<div>email ${data.email}</div>`;

email body += `<div>message ${data.message}</div>`;

mailapp.sendmail({

to: ‘gap*****gmail.com’,

subject: ‘new webform email’,

htmlbody: email body

});

if (validate email (data. email)) {

let rephtml = `<h2>thanks ${data.name}</h2>`;

rephtml += `<div>we will reply shortly. received message id ${data.rowval}</div>`;

mailapp.sendmail({

to: data.email,

subject: ‘thank you for your email’,

htmlbody: rephtml

});

returns true;

} more {

returns false;

}

function validate email (email) {

const re = /s+@s+.s+/;

return re.test(email);

}

testemail() function {

constant value = {

email: ‘gappsc*****@gmail.com’,

name: ‘tester’,

message: ‘hello world’,

row value: 50

logger.log(sendmymail(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(datasheet[0]);

const holder = [];

sheetdata[0].foreach((header, index) => {

if (json[header]) headline[index] = (json[header]);

})

logger.log(holder);

ss.appendrow(header);

}

function doget(e) {

returns contentservice.createtextoutput(json.stringify(e)).setmimetype(contentservice.mimetype.json);

}

Leave a Reply

Your email address will not be published. Required fields are marked *