In this post, we will figure it out how one can send emails using JavaScript. For more code examples and details, check Sending Emails with JavaScript
JavaScript is a programming language that you can use for both front-end and back-end development. When the name JavaScript is used in the context of sending emails, Node.js is the first thing that comes to mind.
We want to change the perspective from the server-side to the client-side. Let’s figure out how you can use JS to send emails from the app that has no back-end.
You can’t send emails using JavaScript code alone due to lack of support for server sockets. For this, you need a server-side language that talks to the SMTP server. You can use JS in conjunction with a server script that will send emails from the browser based on your requests. This is the value we’re going to introduce below.
Traditionally, the server-side of a regular app is responsible for sending emails. You will need to set up a server using back-end technology. The client-side sends a request to the server-side, which creates an email and sends it to the SMTP server. If you’re curious about what happens with an email after that, read our blog post, SMTP relay.
So, why would anyone be willing to go another way and send emails right from the client-side using JavaScript? Such an approach is quite useful for building contact forms or other kinds of user interaction on web apps, which allows your app to send an email without refreshing the page the user is interacting with.
Besides, you don’t have to mess around with coding a server. This is a strong argument if your web app uses email sending for contact forms only. Below, you will find a few options on how to make your app send emails from the client-side.
mailto: for sending form data
Since you can’t send an email directly with JS, you can tell the browser to open a default mail client to do so. Technically, the mailto: method does not send email directly from the browser, but it can do the job.
Check out how the following code example works:
< form action=“mailto:you @yourdmainhere.com” method=“post” enctype=“text/plain” >
FirstName:< input type=“text” name=“FirstName”>
Email:< input type=“text” name=“Email”>
< input type=“submit” name=“submit” value=“Submit”>
The mailto:
method is a rather easy solution to implement but it has some specific drawbacks:
SmtpJS is a free library you can use for sending emails from JavaScript. All you need is an SMTP server and a few manipulations to get things done.
Be aware that your username and password are visible in the client-side script. This can be fixed if you utilize the encryption option provided by SmtpJS. Click the Encrypt your SMTP credentials button and fill in the required fields.
To know more about sending emails using JavaScript, you should check the full Mailtrap article mentioned at the top of this post. There are code samples, examples, and other FAQs
Photo by Mathyas Kurmann on Unsplash
#javascript