Sending Emails with JavaScript

On March 27, 2024
8min 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:

How to send emails in JavaScript: mailto

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

How to send emails in JavaScript: mailto

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.

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 select an email-sending service to connect to

As the Mailtrap Email Delivery Platform is available as an EmailJS integration, we will select it upon creating our EmailJS account and demonstrate how to connect to both its sending and testing solution.

First, you log into your EmailJS account and navigate to Email Services -> Add New Service.

Email JS interface

Next, a popup window will appear where you need to select “Mailtrap” from the available options.

EmailJS choosing a service

You will then be asked to configure the service by providing all the necessary details:

Service ID – Unique ID assigned to the service.

Username and Password – Credentials provided to you by Mailtrap. If you need help retrieving those, please refer to the Mailtrap knowledgebase.

Email Feature – Dropdown menu for selecting whether you want to connect to:

  • Mailtrap Email Testing – an email testing tool used by developers to validate emails and debug/troubleshoot any issues within them through inspecting and debugging. Thanks to Mailtrap Email Testing, test emails caught in staging never reach recipients, except the whitelisted ones. Users of Email Testing at their disposal have automated test flows and scenarios, spam score checking, blacklist reports, HTML/CSS validation, and more features.
  •  Mailtrap Email Sending – an email sending solution consisting of an email API and an SMTP service (both with a smooth and secure setup) that can reach customers’ inboxes just in time (≈ 1 sec, to be more specific). The unique monitoring features Mailtrap Email Sending comes with include helicopter-view dashboards, drill-down email reports for mailbox providers, extended email history with historical data of up to 60 days, email body preview after an email was sent, weekly reports with week-on-week comparison and critical alerts if numbers suddenly drop.

In the example below, we are connecting to Mailtrap’s sending solution.

EmailJS service configuration

With all the details provided, click “Create Service” to finalize this step and have the service listed in your EmailJS dashboard.

EmailJS creating a service
  • Create an email template using the built-in editor

For sending emails, we need to create an email template using the built-in editor. This editor provides plenty of options for content building and other useful features, such as auto-reply, reCAPTCHA verification, and more. 

Note: For those of you that decide to code your own HTML email template. We suggest you read our Guide on How to Build HTML Email.

In the EmailJS dashboard, the editor can be found under Email Templates -> Create New Email Template.

Once opened, there you will be able to define the subject, content, recipient, sender, sender name, as well as the cc and bcc recipient.

Note: When using Mailtrap Emal Sending, the sender email has to be from the same domain you added and verified when setting up your Emal Sending account.

  • Test the template

If you want to test how your template looks as well as the email service you configured, you can run a test using the “Test It” option.

EmailJS default email template

Once clicked on, the “Test It” option will open a new popup window where you need to provide some details for the test, such as what service should be used and the values for template parameters.

EmailJS testing the email template

Run the test, and if everything goes as expected, you will get “200 OK” as a result, which means the email was sent successfully.

Once you’re done with testing, close the popup and save your template.

  • Install EmailJS SDK

To complete the installation process for EmailJS SDK, you have two options:

Using npm:

$ npm install @emailjs/browser --save

Using bower:

$ bower install @emailjs/browser --save

If you intend to use EmailJS on your website, then you will need to paste the following code before the closing tag:

<script type="text/javascript"
      src="https://cdn.jsdelivr.net/npm/@emailjs/browser@3/dist/email.min.js">
</script>
<script type="text/javascript">
   (function(){
      emailjs.init("YOUR_PUBLIC_KEY");
   })();
</script>
  • Send the email

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

emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', '#myForm') //use your Service ID and Template ID
  .then(function (response) {
    console.log('SUCCESS!', response.status, response.text);
  }, function (error) {
    console.log('FAILED...', error);
  });

If you want the full code for sending an email straight from the browser using EmailJS and a template you created, you can use the example below:

<script type="text/javascript"
       src="https://cdn.jsdelivr.net/npm/@emailjs/browser@3/dist/email.min.js">
</script>
<script type="text/javascript">
  (function () {
     emailjs.init("YOUR_PUBLIC_KEY");
  })();
</script>
<script>
  var templateParams = {
    from_name: 'Sender',
    message: 'Test Message'
  };

  emailjs.send('email-service-ID', 'email-template-ID', templateParams)
    .then(function (response) {
      console.log('SUCCESS!', response.status, response.text);
    }, function (error) {
      console.log('FAILED...', error);
    });
</script>

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).

Note: Using EmailJS is an option for frontend-only applications that are not supported by a backend server. In case your application does have a backend server, you can use solutions such as Mailtrap Email Sending, described in detail in the section below, for sending emails with JavaScript.

Mailtrap Email Sending

In the EmailJS section of this article, we briefly mentioned Mailtrap Email Sending as a reliable sending solution. So how does one start using it in their JavaScript application?

First, you need to create a Mailtrap account.

Then, in your account, navigate to Sending Domains to add and verify your domain as described in the Mailtrap knowledgebase

Once that is done, you can proceed with installing the official Mailtrap Node.js client using the command below:

npm install mailtrap

Since we’ll be using environment variables to keep our API credentials, we also need the “dotenv” package, which can be installed using the command below:

npm install dotenv

Upon installation, create a file called .env and add your Mailtrap Email Sending credentials to it as follows:

MAIL_DRIVER=smtp
MAIL_HOST=send.api.mailtrap.io
MAIL_PORT=2525
MAIL_ENCRYPTION=tls
MAIL_TOKEN=*******************
API_MAIL_FROM_ADDRESS="name@domain.com"

Note: To find your API key, go into your Mailtrap account and navigate to Settings – > API Tokens.

Next, you need to create a file called api.js which should contain the code below.

"use strict";
require('dotenv').config()
const { MailtrapClient } = require("mailtrap");

let env_variables = process.env;

const client = new MailtrapClient({ token: env_variables.MAIL_TOKEN });

const sender = { name: "Mailtrap API Test", email: env_variables.API_MAIL_FROM_ADDRESS };

client
  .send({
    from: sender,
//use a real mail for the to object
    to: [{ email: 'user@mailtrap.io' }],
    subject: "Hello from Mailtrap!",
    text: "Welcome to Mailtrap Sending!",
  })
  .then(console.log, console.error);

Finally, to run the code, run the command below in the command line of your development environment.

node api

And that’s it! Your email should now be sent off to the specified recipient through Mailtrap Email Sending from your JS application.

Sending an HTML email with an image in the body

Using the code in the section above, we sent a simple plain text email. If you want to send an email that is a bit more complex, let’s say in HTML format with an image in the body, you will need to create a new .js file (api_attachment.js, for example) and copy-paste this code into it:

"use strict";
require('dotenv').config()

//use the filesystem and path to access and add the attachment 
const fs = require("fs");
const path = require("path");
const { MailtrapClient } = require("mailtrap");

let env_variables = process.env;

const client = new MailtrapClient({ token: env_variables.MAIL_TOKEN });

const sender = { name: "Mailtrap API Test", email: env_variables.API_MAIL_FROM_ADDRESS };


const imageFile = fs.readFileSync(path.join(__dirname, "image.png"));

client
  .send({
    category: "Sending Email using Javascript",
    custom_variables: {
      mailer: "Javascript",
      year: 2022,
      anticipated: true,
    },
    from: sender,
    //you can send to multiple emails
    to: [{ email: 'raphealenike@gmail.com' }],
    subject: "Hello from Mailtrap!",

    //html code can be attached to the mail
    html: `
    <!doctype html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      </head>
      <body style="font-family: sans-serif;">
        <div style="display: block; margin: auto; max-width: 600px;" class="main">
          <h1 style="font-size: 18px; font-weight: bold; margin-top: 20px">This email was send from Mailtrap Email API!</h1>
          <p>Inspect it using the tabs you see above and learn how this email can be improved.</p>
          <img alt="Inspect with Tabs" src="cid:image.png" style="width: 100%;">
          <p>Explore sending emails from your application of your choice with Mailtrap Email API</p>
          <p>We look forward to your exploration experience</p>
        </div>
        <style>
          .main { background-color: white; }
          a:hover { border-left-width: 1em; min-height: 2em; }
        </style>
      </body>
    </html>
  `,
  //enable viewing of attached image in the mail body
    attachments: [
      {
        filename: "image.png",
        content_id: "image.png",
        disposition: "inline",
        content: imageFile,
      },
    ],
  })
  .then(console.log, console.error);

Note: Do keep in mind that you need to make the necessary changes in the code, such as updating the recipient name, the attachment filename, and so on.

Then, just like with we did for the plain text email, run the following command to run the code and send off the email.

node api_attachment

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.