Send Mail Using JavaScript

Introduction

Today, we are going to learn something related to JavaScript. There were many requirements, like where you just had to send a mail using JavaScript, and you couldn't use any REST API or any other platform to create your platform or server-side application to send a mail. 

So, to resolve that, we can use ElasticEmail to set up our own SMTP Hosting and send mail using the same. So, let's begin with creating our ElasticEmail account and setting up the host, and sending mail using it,

We have to follow the steps to set up the ElasticeEmail Account.

Step 1 

Go to the ElasticeEmail. Click Here...

Step

Send Mail Using JavaScript

Step 3

Select Email API and click on the "Try For Free" Button; on the next page, add all required details.

Send Mail Using JavaScript

Step 4

After completing the Signup process, you will get the following Dashboard shown in the below picture. 

Send Mail Using JavaScript

Step 5

Once you are done creating your Elastic email account, you will get an activation mail, as shown below.

Send Mail Using JavaScript

Step 6

Click "ACTIVATE MY ACCOUNT" and log in with your required credentials. Once it is Activated, you will get the following Dashboard.

Send Mail Using JavaScript

Creating a Hosting or SMTP Relay

Step 1

Now, click "Connect to SMTP API" and then "Create". Add your Username and click on Create.

Send Mail Using JavaScript

Step 2

Once you click Create, it will take some time, and you will get a popup containing the SMTP Details as shown in the image.

Send Mail Using JavaScript

Once we are done setting up our SMTP, we can move forward to write our business logic for JavaScript code to send Mail using our created SMTP.

You can use the following code to reference sending mail using JavaScript.

Demo.JS

function sendEmail() {
	Email.send({
		Host: "smtp.elasticemail.com",
		Username : "<YOUR SMTP USERNAME>",
		Password : "<YOUR SMTP PASSWORD>",
		To : '<EMAIL TO SEND A MAIL>',
		From : '<EMAIL FROM WHICH YOU HAVE LOGGED IN TO ELASTICEMAIL>', // put a real email address that is verified
		Port:'2525',
		Subject : "Hello",
		Body : "Hello",
	}).then(
		message => {
			alert("mail sent successfully");
			console.log(message);
		}
	);
}

Demo.HTML

<html>
	<head>
		<script src="https://smtpjs.com/v3/smtp.js"></script>
		<script src="Demo.js"></script>
	</head>
	<body>  
		<form method="post">
			<input type="button" value="Send Email" onclick="sendEmail()"/>
		</form> 
	</body>
</html>

We must load the SMTP js to send a mail using the SMTP we have created. I am using the button click event to send a mail, but you can directly send a mail when you load JavaScript.

After executing and clicking the Send Email Button, I get the following mail inside my Gmail account.

Send Mail Using JavaScript

I hope this blog will help you send emails using the Elastic email SMTP Relay.

Thank you.