How to Send Emails From Javascript?

Published on 2019-09-19· Updated on 2024-04-11

The author voluntarily contributed this tutorial as a part of Pepipost Write to Contribute program.

Introduction

Smtp.js is a free JavaScript library that helps you to send emails using client-side JavaScript without requiring server-level configurations. 

By including a small code snippet in the header of your HTML, the SMTPJS package facilitates routing of emails from the front end to an SMTP server. The library offers Email.send() method, which enables sending emails directly from JavaScript.

SMTP is a protocol for sending emails to the intended server and recipient. Sending emails directly through a browser is not advisable since it involves data sharing and needs secure connections and user credentials. However, if you possess your own SMTP server and a reliable validator, you may send emails from JavaScript (browser).

Prerequisites

  • Create SMTP Server: Go to  https://smtpjs.com/. You will get a "Setup an SMTP server " option.
  • Select your favorite Editor (Sublime, Visual Code, CLI editors, etc.)
  • Have a Browser (to test the code)

How to configure and use Gmail SMTP to send emails from Javascript

Before sending emails using Gmail's SMTP Server, you must make a few security and permission level settings under your Google Account Security Settings.

1. Open your Gmail account settings. Click on Sign-in and Security. Navigate to connected apps and sites and enable two-factor authentication. 

2. Create an app password. The app password should be the password you use in your SMTP settings. You can generate an app password by visiting this page while logging into your Google account.

Note: It may take an hour or more to reflect any security changes

After completing the settings, your Google SMTP server configurations will resemble the following:

  • SMTP Server/Hostname: smtp.gmail.com
  • SMTP Username: [Your Gmail Address]
  • SMTP password: [Your Gmail Password]
  • SMTP Port: 587
  • TLS/SSL: Required

Now, let's proceed with the code for sending emails from JavaScript.

Writing JavaScript and integrating with Gmail to send mail

Step 1

Create two files in a folder as given below:

  • index.html
  • index.js 

Step 2

Step 2

Download the smtp.js file or add a script tag pointing to https://smtpjs.com/v3/smtp.js.  Upon including the script, a global variable named ‘Email’ will be available in JavaScript, provided by smtp.js. You can now open the index.html file and incorporate the SMTPJS library using the following code snippet:

#index.html
<head>
    <script src="https://smtpjs.com/v3/smtp.js"></script>  
</head>

 

Step 3

The next step is to include a script file that will have the SMTP details and email template. Add the file name `index.js` to it.

#index.html
<head>
	<script src="https://smtpjs.com/v3/smtp.js"></script>
	<script src="index.js"></script>
</head>

Step 4

Add a button in the HTML body, this will trigger the mail configured in a javascript function:

#index.html
...
<body>  
	<form method="post">
		<input type="button" value="Send Email" onclick="sendEmail()"/>
	</form>  
</body>

 

Step 5

Now, create a new file named index.js, the JavaScript function responsible for sending emails using smtpjs.com. Remember to include this file in the HTML (index.html) file, as you did before.

//index.js  
function sendEmail() {
	Email.send({
	Host: "smtp.gmail.com",
	Username : "<sender’s email address>",
	Password : "<email password>",
	To : '<recipient’s email address>',
	From : "<sender’s email address>",
	Subject : "<email subject>",
	Body : "<email body>",
	}).then(
		message => alert("mail sent successfully")
	);
}

The mentioned configurations enable sending a POST request to the SMTP server and receiving a response indicating success or failure. You are now ready to proceed.

Open the folder containing the index.html and index.js files. Right-click on the index.html file and select "Open in the browser". Wait for the page to load, then click on the "Send Email" button.

Before sending the email, it is recommended to test various aspects such as email flow, spam score, HTML/CSS validation, and more with the help of our free tool, Email Dojo. After testing, proceed to send the email successfully.

Step 6 (Optional)

You can also send emails to multiple users by utilizing the 'TO' property, which can accept an array of recipients instead of a single entry. Here's a sample to illustrate this functionality:

function sendEmail() {
	Email.send({
	Host: "smtp.gmail.com",
	Username : "Your Gmail Address",
	Password : "Your Gmail Password",
	To : 'recipient_1_email_address, recipient_2_email_address',
	From : "sender’s email address",
	Subject : "email subject",
	Body : "email body",
	}).then(
		message => alert("mail sent successfully")
	);
}

 

Step 7 (Optional)

You can also send emails with attachments using the following code in JavaScript.

function sendEmail() {
  Email.send({
  Host: "smtp.gmail.com",
  Username : "Your Gmail Address",
  Password : "Your Gmail Password",
  To : 'recipient’s email address',
  From : "sender’s email address",
  Subject : "email subject",
  Body : "email body",
  Attachments : [
  	{
  		name : "smtpjs.png",
  		path:"https://networkprogramming.files.wordpress.com/2017/11/smtpjs.png"
  	}]
  }).then(
  	message => alert("mail sent successfully")
  );
}

 

Note

Here is an interesting observation:  you will not see any exceptions upon clicking the send button. A ‘200 OK’ status is returned as the connection to Gmail is established on smtpjs.com.  This happens because JavaScript code merely sends the content and configurations to smtpjs.com, while the interaction with Gmail remains hidden from the front end. 

Note: This code only runs for elastic mail SMTP hosts. Other service providers will get ‘200 OK’ in response when an SMTP connection is established and not for the successful delivery of email. Due to abuse (spam/phishing) SMTPJS.com has been limited to trusted SMTP providers. Currently, the recommended SMTP provider is ElasticEmail; other SMTP providers may be considered in the future.

For your reference, below is the complete working code.

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script src="https://smtpjs.com/v3/smtp.js"></script>  
	<script type="text/javascript">
		function sendEmail() {
			Email.send({
				Host: "smtp.gmail.com",
				Username : "<sender’s email address>",
				Password : "<email password>",
				To : '<recipient’s email address>',
				From : "<sender’s email address>",
				Subject : "<email subject>",
				Body : "<email body>",
			})
			.then(function(message){
				alert("mail sent successfully")
			});
		}
	</script>
</head>
<body>  
	<form method="post">
		<input type="button" value="Send Email" onclick="sendEmail()"/>
	</form>  
</body>
</html>

Conclusion

In this tutorial, we explored how to send emails from JavaScript without complex server setups. By following our step-by-step guide, you can effortlessly configure Gmail SMTP, add email attachments, and integrate email functionality into your web applications. We are a community of email enthusiasts. If you have further queries, feel free to drop an email to [email protected] , and we would be happy to help you.
Happy Coding...

Grade My Email
Check your spam now?

Netcorecloud's toolkit is the solution to all your email problems.

Vishal Chauhan

You can also explore

Netcore connects & unifies your data across all sources, connects to your marketing channels and provides you with control over AI Powered automation and personalization.

Deploy emails that are
screenshot worthy!

Stop settling for static emails - use Netcore's platform to create dynamic, interactive emails that convert.
Let's Deploy
Get Started Now