Welcome folks today in this blog post we will be sending
emails automatically to the gmail account using html
form in browser using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new code.gs
file and copy paste the following code
code.gs
1 2 3 4 |
function doGet() { var template = HtmlService.createTemplateFromFile('index'); return template.evaluate(); } |
As you can see in the above code we are loading the index.html
file when the user open the web
app in the browser. This doGet()
automatically executes whenever app is deployed.
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<form> <label for="to">To:</label> <input type="email" id="to" name="to" required><br> <label for="subject">Subject:</label> <input type="text" id="subject" name="subject" required><br> <label for="message">Message:</label><br> <textarea id="message" name="message" required></textarea><br> <input type="submit" value="Send"> </form> <script> document.querySelector('form').addEventListener('submit', (event) => { event.preventDefault(); const to = document.getElementById('to').value; const subject = document.getElementById('subject').value; const message = document.getElementById('message').value; google.script.run.sendEmail(to, subject, message) .withSuccessHandler(success) .withFailureHandler((error) => alert(`Error: ${error}`)); }); function success(){ alert("message sent") } </script> |
As you can see we have the simple form
where we allow the user to enter the information to send the email and then we have the javascript
code to actually send the request to the apps script code.
1 2 3 |
function sendEmail(to, subject, message) { GmailApp.sendEmail(to, subject, '', { htmlBody: message }); } |
As you can see in the above code we are using the GmailApp to send the email
to the specified user.
Deploying the Web App