Stand with Ukraine 🇺🇦 Donate to support

Sending Emails with JavaScript

On January 06, 2022
9min read
Artur Hebda Full Stack Developer @Railsware

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 even blogged about how to send emails with Node.js. In this article, 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 an app that has no back-end.

Can I send emails with JS or not?

You can’t send emails using JavaScript code alone due to the 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.

Why you might want to send emails with JS

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">
</form>

When you launch it in the browser, you’ll see the following:

Once the data has been submitted, the browser opens a default mail client. In our case, this is Gmail.

The mailto:method is a rather easy solution to implement, but it has some specific drawbacks:

  • You can’t control the layout of the data since the data is submitted in the form sent by the browser.
  • mailto: doesn’t protect your email address from being harvested by spambots. Some time ago, this could be mitigated by constructing a link in JS. These days, more and more bots run JS and do not rely on HTML rendered by the server alone.

SmtpJS.com – true email sending from JavaScript

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. 

But, before you proceed with sending on production, you need to test on staging. That is why, we will use the SMTP server credentials provided by Mailtrap’s Email Sandbox, which will serve as a virtual inbox for receiving the test emails. 

But, Email Sandbox is more than just a virtual inbox. Instead, it’s an email testing tool used by developers to validate emails and debug/troubleshoot any issues within them through inspecting and debugging.

Thanks to Email Sandbox, test emails caught in staging never reach real recipients. Meaning, regardless of how long or complex your email testing process is, during it, you are never at risk of spamming real recipients with them.

Users of Email Sandbox have at their disposal, automated test flows and scenarios, spam score checking, blacklist reports, HTML/CSS validation, and more features. 

We will talk in-depth about the HTML/CSS validation once we touch upon HTML emails. For now, let’s get back to the steps of sending your first test email with SmtpJS while using Email Sandbox’s SMTP server credentials.

  • Get a free Mailtrap account and log into the dashboard. Once logged in, go to Sandbox -> Inboxes and find the SMTP Settings section. There, you should see a tab labeled “Show Credentials”, revealing the Mailtrap SMTP server credentials. Keep it open so you can use it in the code examples below.

  • Create an HTML file (for example, test.html) with the following script:
<script src="https://smtpjs.com/v3/smtp.js">
</script>
  • Create a button that will trigger the JavaScript function.
<input type="button" value="Send Email" onclick="sendEmail()">
  • Write the JS function to send emails via SmtpJS.com. This is the step where you need to include the credentials you retrieved earlier.
function sendEmail() {
Email.send({
    Host : "smtp.mailtrap.io",
    Username : "<Mailtrap username>",
    Password : "<Mailtrap password>",
    To : 'recipient@example.com',
    From : "sender@example.com",
    Subject : "Test email",
    Body : "<html><h2>Header</h2><strong>Bold text</strong><br></br><em>Italic</em></html>"
}).then(
  message => alert(message)
);
}

If you have multiple recipients, you can specify an array of email addresses in the To: property.

  • Run test.html in the browser and send your email.

The drawback with the code example above is 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. So, click the Encrypt your SMTP credentials button and fill in the required fields. 

After that, press Generate security token to use it in your JS function instead of SMTP server settings:

SecureToken : "<your generated token>"

Code sample for sending an HTML email

Now, we will take things a step further and show you code examples for sending an HTML email and an email with an attachment. 

As mentioned earlier, Mailtrap Email Sandbox allows you to validate HTML/CSS in its HTML Check tab.

With HTML Check, it’s possible to see the level of support of top email clients for your HTML/CSS attributes. This will give you an idea of how your emails will be rendered in different inboxes.

For each email analyzed using HTML Check, a report is generated consisting of a market support percentage breakdown at the top and email client support for individual HTML elements/CSS rules at the bottom, with links to code lines containing errors and notes with additional information. 

So, once you send your HTML email using the code below, feel free to validate it using Email Sandbox’s HTML Check feature.

<script src="https://smtpjs.com/v3/smtp.js"></script>
<input type="button" value="Send Email" onclick="sendEmail()">
<script>
function sendEmail() {
	Email.send({
    SecureToken : "<your generated token>",
    To : 'recipient@example.com',
    From : "sender@example.com",
    Subject : "Test Email",
    Body : "<html><h2>Header</h2><strong>Bold text</strong><br></br><em>Italic</em></html>"
    }).then(
        message => alert("mail sent successfully")
    );
}
</script>

Code sample for sending an email with attachments

For sending an email with an attachment, use the Attachments property, as follows:

<script src="https://smtpjs.com/v3/smtp.js"></script>
<input type="button" value="Send Email" onclick="sendEmail()">
<script>
function sendEmail() {
Email.send({
    SecureToken : "<your generated token>",
    To : 'recipient@example.com',
    From : "sender@example.com",
    Subject : "Test Email",
    Body : "<html><h2>Header</h2><strong>Bold text</strong><br></br><em>Italic</em></html>",
	Attachments : [
	{
		name : "smtp.png",
		path : "https://…/smtp.png"
	}]
	}).then(
  		message => alert(message)
	);
}
</script>

EmailJS

EmailJS.com was already featured in our blog post, Sending Emails with ReactJS. This service allows you to connect your email service, build an email template, and send it from JavaScript without any server code. So, let’s check out the scope.

  • Create an account and choose an email sending service to connect to. There are, of course, standard solutions available such as Gmail or Outlook. But, you might also consider using a sending solution like Mailtrap Email API for the range of benefits it comes with, including a custom server and easy-to-obtain SMTP credentials, just to name a few. As we are still sending just test emails, we will stick with the Mailtrap Email Sandbox SMTP credentials used thus far.
  • Create an email template using the built-in editor. The editor provides plenty of options for content building and other useful features, such as auto-reply, reCAPTCHA verification, and more. It’s also necessary to understand the basics of coding your own HTML email template. For this, read our Guide on How to Build HTML Email. Once this is done, click Save.

One of the major benefits of EmailJS.com is that the typical email attributes are hidden. The template includes the recipient field, and it cannot be overridden from JS, so you send the template you have configured previously.

  • Now you need to install EmailJS SDK. This can be done with npm:
npm install emailjs-com --save
  • Or bower:
bower install emailjs-com --save
  • If you need to use EmailJS on your website, paste the following code before the closing tag:
<script type="text/javascript"
        src="https://cdn.jsdelivr.net/npm/emailjs-com@2.4.0/dist/email.min.js">
</script>
<script type="text/javascript">
   (function(){
      emailjs.init("YOUR_USER_ID"); //use your USER ID
   })();
</script>
  • The actual email sending can be carried out via two methods: emailjs.send or emailjs.sendForm. Here are the code examples for both of them:

emailjs.send

var templateParams = {
    name: 'James',
    notes: 'Check this out!'
};
emailjs.send('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', templateParams) //use your Service ID and Template ID
    .then(function(response) {
       console.log('SUCCESS!', response.status, response.text);
    }, function(error) {
       console.log('FAILED...', error);
    });

emailjs.sendForm

var templateParams = {
    name: 'James',
    notes: 'Check this out!'
};
emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', templateParams) //use your Service ID and Template ID
    .then(function(response) {
       console.log('SUCCESS!', response.status, response.text);
    }, function(error) {
       console.log('FAILED...', error);
    });

Code sample for sending emails

Let’s check whether EmailJS.com works by sending an email straight from the browser. We’ve set up a virtual inbox with Email Sandbox and built a simple template. Now, we need to create an HTML file with the following code:

<script type="text/javascript"
      src="https://cdn.jsdelivr.net/npm/emailjs-com@2.4.0/dist/email.min.js">
</script>
<script type="text/javascript">
   (function(){
      emailjs.init("<USER-ID>"); //Insert your User ID
   })();
</script>
<script>
	var templateParams = {
    name: 'Sender',
    notes: 'Test email'
};
emailjs.send('<email-service-ID>', '<email-template-ID>', templateParams) //Insert your email service ID and email template ID
    .then(function(response) {
       console.log('SUCCESS!', response.status, response.text);
    }, function(error) {
       console.log('FAILED...', error);
    });
</script>

Run it in the browser and check your virtual inbox. It works!

Pricing

EmailJS offers a free subscription plan that allows you to send up to 200 emails per month using only two templates. In addition, you’ll have a limited list of contacts and email size (up to 50Kb). Higher quotas are available for paid subscriptions: Personal ($5/month), Professional ($15/month), and Business ($50/month).

Mailtrap Email API

If you need fast, easy, and automated email sending in JavaScript, you should be using an email API. Plus, depending on the API you go for, you might also get to enjoy email analytics.

An email API that fits the above description is the one offered by Mailtrap as part of its Email Delivery Platform along with Email Sandbox.

Mailtrap Email API is best described as a reliable email sending service you can set up and use without any hassle whatsoever. 

With a sending throughput of up to ~10000 emails per second, Email API will meet your sending needs. And, thanks to its batch of actionable analytics features, it will also enable you to find and remove early-stage sending issues that might be dragging down your email deliverability.

So, how do the actionable analytics features work in practice? 

First, you have timely deliverability alerts, which notify you each time there is a deliverability issue and tell you where to look for it. Also, deliverability-wise, you receive weekly reports.

Next, there are dashboards with critical metrics that provide you with insight into the state of your email infrastructure.

And lastly, we’ll mention the 60-day email logs, which are great for improved troubleshooting.

Apart from the benefits of actionable analytics, Email API users also have access to webhooks, dedicated IPs, automatic IP warmup, suppression lists, and more.

So, to start using Email API from within your JavaScript app, these are the steps you need to complete:

Step #1 – Have an active Mailtrap account.

Step #2 – Add and verify your domain, as demonstrated in the video below.

Step #3 – Create an API token

Step #4 – Import Axios library

// HTML (index.html)
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Mailtrap Email API</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="./script.js" type="text/javascript"></script>
  </head>
  <body>
    <button type="button" name="button" onclick="sendEmail()">Send email</button>
  </body>
</html>

Step #5 – Send email with JavaScript

// JavaScript (script.js)
function sendEmail() {
axios({
	"method": "POST",
	"url": "https://send.api.mailtrap.io/api/send",
	"headers": {
		"Api-Token": "7d291ae20ba717497f0ea1ae9fa2158c",
		"Accept": "application/json",
		"Content-Type": "application/json"
	},
	"data": {
		"to": [
			{
				""email": "receiver@mail.com",
				"name": "Reveiver Name"
			}
		],
		"subject": "Email Subject",
		"html": "<p>HTML Email content</p>",
		"from": {
"email": "sender@mail.com",
			"name": "Sender Name"
		}
	}
})
 
}
 
// Email API JSON Response 
{
"success": true,
"message_ids": [
"9390c7fd-15ef-14ea-51d4-9ac0f0a58ae2"
]
}

As Mailtrap supports SMTP, you can take a route different from the API integration and simply set Mailtrap as the SMTP server in your project, app, or email sending service to start shooting out emails.

The SMTP credentials are very easy to get from the API and SMTP Integration section under Email API-> Sending Domain.

To wrap up

Although sending emails is a server-side thing, you can refrain from dealing with server-side coding. SmtpJS and EmailJS are two actionable solutions to streamline your front-end and make it able to send emails. EmailJS is better because it hides typical email attributes, and you are able to send whatever templates you have configured before. The mailto: method is different, but it can also be useful in some cases. If you, however, have changed your mind and are willing to set up back-end for your app, check out one of our dedicated blog posts:

Article by Artur Hebda Full Stack Developer @Railsware

Comments

4 replies

Ariyibi Baseet

This code works for me

Piotr Malek

Good to hear, Ariyibi. Have a good day 🙂

Akshay

Hi, do you know how to integrate Google reCaptcha with emailJS? just using the keys in their settings isn’t working. My form is on a static html site.

sajid

this code is not working

Comments are closed.