How to send Emails from JavaScript App
In this article, we will learn How to send Emails from JavaScript App. The project will be using Simple Mail Transfer Protocol which is a free JavaScript library. By creating an SMTP server we will only be able to send emails as the protocol only works for outgoing emails.
If you’ll be using Gmail apart from professional email, you need to make two simple changes to your Google account in order to avoid conflicts while executing.
- Enabling less secure apps to access Gmail so that an app coded by you can send Emails directly. You can go through the previous guide (opens in a new tab) for a better explanation of this.
You can enable this by clicking on the link: Enable (opens in a new tab)
- Remove any multistep Authentication (opens in a new tab) to attain hassle-free mail processing via SMTP.
Code
Let’s first create the Index.html file which will contain the below module. Later on, we will keep adding the necessary scripts and snippets.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Send Email</title>
</head>
<body>
<form method="post" name="Form">
<input type="Password" name="password" placeholder="Password" /><br />
<input type="Email" name="Reciever" placeholder="Reciever Adress" /><br />
<input
type="text"
name="Message"
placeholder="Enter Content"
id="Message"
/><br />
<input type="button" value="Send Email" onclick="sendEmail()" />
</form>
</body>
</html>
Related: How to send Emails from NodeJS App
SMTP JS
Import the SMTPJS via adding the below script to your HTML file.
<script src="https://smtpjs.com/v3/smtp.js"></script>
Functioning
Create a function named ‘sendEmail’ and include the ‘Host’ name, if you’re using Gmail keep the default. Now change the Username, Password, sender, receiver, subject, and Email body respectively.
By tweaking, you can dynamically get all the fields from the HTML form shown before that way the rigidness of the application will retain.
function sendEmail() {
Email.send({
Host: "smtp.gmail.com",
Username: "sender@email.com",
Password: "Enter your password",
To: "receiver@email.com",
From: "sender@email.com",
Subject: "Sending Email from JavaScript",
Body: "This is a demo Email"
}).then(function (message) {
alert("Email sent successfully");
});
}
Conclusion
This was a tutorial explaining how to send emails from a Javascript app, which works without any backend technology. Previously we’ve covered how to send Emails from NodeJS which includes direct backend logic.
I hope this tutorial was helpful to you, If you’re having trouble reach us in the comment section & we’ll try to solve your queries as soon as possible.