If you're writing a front-end web app with Javascript, it's very likely that you'll need to create a contact form. A contact form is a crucial part of marketing, lead generation, and communicating with users.



Not only does a contact form drive sales, but it also helps you stay in touch with users who are having problems so you can quickly and effectively fix bugs and provide customer support

Sending an email from your front-end Javascript application is not as easy as sending a regular AJAX request. There are a few more steps involved because email communication must remain secure. Violating email communication protocols puts you at risk of being labeled a spammer.

This article will look at two ways of sending email from a Javascript app: using the mailto HTML attribute, and using SMTPJS with ElasticEmail.  

Don't reinvent the wheel.
Abstract's APIs are production-ready now.

Abstract's suite of API's are built to save you time. You don't need to be an expert in email validation, IP geolocation, etc. Just focus on writing code that's actually valuable for your app or business, and we'll handle the rest.

Get started for free

What is SMTP?

SMTP (or Simple Mail Transfer Protocol) is the communication layer that handles email. It outlines a set of rules for sending and receiving emails, just as HTTP (Hyper Text Transfer Protocol) outlines the rules for sending and receiving data packages on the web.


An SMTP server handles SMTP traffic. SMTP servers perform a lot of important functions, mostly to do with preventing spam and other bad actors from invading our emails and ruining our days. 

An SMTP server works like this:

  1. The server receives email information from a client (usually on Port 25.) 
  2. It breaks the email address of both sender and recipient into two parts: the username and the domain. 
  3. For example, in the address abstractapi@gmail.com, the username is abstractapi and the domain is gmail.com
  4. It examines the domain of the sender and the domain of the recipient. If both are under the same domain (i.e. gmail.com) it sends the email via that domain’s preferred method (i.e. POP or IMAP.)
  5. If the domain of the sender and recipient are different, the server checks to see that the sender’s email address is an active and valid email. This prevents spam.
  6. If the sender’s address is valid, the server sends the email data to the recipient’s SMTP server. That server handles delivering the email to the recipient.


Javascript that runs in the browser isn't allowed access to Port 25. This prevents Javascript apps from being able to send spam to people. If you're running a serverless frontend through Gatsby or another static site application, you'll need to send your email data to an SMTP server.

You can configure your own SMTP server and send an email that way. There are plenty of plugins and packages for Node and other backend languages that allow you to do this. However, it can be difficult and time-consuming. It's easier to have someone else host the server for you.

Send Emails Using Mailto

mailto is an href redirect that you can add to the <a> anchor element. It works like a regular href link, but instead of opening a normal link, it opens an email client on the user’s device. The mailto link is the easiest way to send an email from a front-end Javascript app.

Add the mailto link to an anchor element


<a href="mailto:email@example.com">Click to Send an Email</a>
 

Put the email address you're sending to after mailto: as part of the string.

When the user clicks on the anchor element, mailto will open the user’s default email client and populate the “recipient” field with the intended email.

Mailto also lets you add a default subject, message, and cc/bcc as a query string.



<a href="mailto:email@example.com?subject='Hello from Abstract!'&body='Just popped in to say hello'">Click to Send an Email</a>
 

Use string interpolation to add dynamic content.


<a href="mailto:`{email}`?subject={subject}&body={body}">Click to Send an Email</a>

It's very easy to send emails this way. Unfortunately, it's not the best solution.

You can't send emails that look great this way. The most you can do is get a string of text with some dynamically added content.

mailto will always open a device's default email client, even if it's not the provider that the user typically uses. Furthermore, if the user doesn't have any email service installed on their device, mailto won't have anything to open at all and it won't work.

Finally, some spammers use bots to search the web for mailto links and then use those bots to spam mail servers.

So, while it's very quick and simple to implement, mailto is not usually the best way to create a robust email from a javascript solution in your app.

Validate Emails Using AbstractAPI

An additional step that would make the mailto redirect more secure against spammers would be validating the sending and receiving email addresses before you send the email. To do this, you could use a service like AbstractAPI.

AbstractAPI’s  Email Verification and Validation API does more than just validate that a given email is formatted correctly. It also runs checks against databases to determine whether the address is active, whether the address can be delivered to, whether the address is a free or disposable email address, or a role-based account, and whether it is SMTP valid and MX records are good.

Let’s add an email validation step to our Javascript application.

Acquire an API Key

Navigate to the API’s Get Started page. Click “Get Started.”



You’ll be asked to sign up by providing a valid email address and password. If you've already signed up, you may need to log in. Once you’re in, you’ll land on the API’s dashboard, where you’ll see your API key and links to documentation and pricing.

Use Your API Key to Send a Request to the API

Use Fetch to send a GET request to the AbstractAPI endpoint, passing it the email address we want validated. Write a function called sendEmailValidationRequest that accepts an email as a parameter and sends the email to the API. 



const apiKey = 'YOUR_API_KEY';

   const apiURL = 'https://emailvalidation.abstractapi.com/v1/?api_key=' + apiKey

   const sendEmailValidationRequest = async (email) => {
       try {
           const response = await fetch(apiURL + '&email=' + email);
           const data = await response.json();
           console.log(data);
       } catch (error) {
           throw error;
       }
   }

The response data should look something like this:



{
  "email": "eric@abstractapi.com",
  "autocorrect": "",
  "deliverability": "DELIVERABLE",
  "quality_score": "0.80",
  "is_valid_format": {
    "value": true,
    "text": "TRUE"
  },
  "is_free_email": {
    "value": false,
    "text": "FALSE"
  },
  "is_disposable_email": {
    "value": false,
    "text": "FALSE"
  },
  "is_role_email": {
    "value": false,
    "text": "FALSE"
  },
  "is_catchall_email": {
    "value": true,
    "text": "TRUE"
  },
  "is_mx_found": {
    "value": true,
    "text": "TRUE"
  },
  "is_smtp_valid": {
    "value": true,
    "text": "TRUE"
  }
}

Based on the response, we can decide whether or not to use the email address in our mailto link. That might look something like this:



   const sendEmailValidationRequest = async (email) => {
       try {
           const response = await fetch(apiURL + '&email=' + email);
           const data = await response.json();
           const isValidSMTP = data.is_smtp_valid.value;
           if (isValidSMTP) {
               // use the email address in the mailto link
           } else {
               // show the user an error
           }
       } catch (error) {
           throw error;
       }
   }

Now, we know at least that the addresses we are using are not spam email addresses. We can't do much about the formatting of the emails, however.

Send Emails in a Javascript App Using SMTPJS and ElasticEmail

A better solution that using mailto is to use a third-party library like SMTPJS. SMTPJS is a package that routes emails from your front end to an SMTP server. All you need to do is include a small snippet of code in the header of your HTML.

The library provides an Email.send() method that is used to send email from Javascript.

The slight catch with using this service is that you need to have your own server set up and running. Fortunately, ElasticEmail allows you to spin up a free server quickly and easily. Let's take a look at the process of setting up your Javascript app to send emails using these two services.

Sign Up for An ElasticEmail Account

You can sign up for an ElasticEmail account for free and use it to send up to 100 emails. After the free trial is over, plans start at $15/month.

https smtpjs.com v3 smtp.js

Head to elasticemail.com and click "Try for Free." Alternatively, you can start your journey at SMTPJS.com and they will direct you to the ElasticEmail signup page.

https smtpjs.com v3 smtp.js login

Sign up using your preferred email address. This is just for communication and authentication with the app.

Create an SMTP Server

Click on "My Account" in the bottom left corner. You'll be taken to a page with settings, billing, profile, etc. Click "Settings."


https smtpjs.com v3 smtp.js settings


Here, you'll see all the configuration options for your account. Click on "Create SMTP Credentials."



You'll be asked to input your username, which is the email address you used to sign up for the account.

Once you do that, and click "Create" you'll see a modal popup containing the credentials for your new server. Copy the password and put it somewhere safe - once you close the modal you will no longer have access to it.

The server will run on port 2525 by default.


Use Server Credentials to Make an SMTP Request from a Javascript Function

Head back to SMTPjs.com and copy the src https smtpjs.com v3 code snippet for your app.





Paste the src https smtpjs.com v3 snippet into the header of your HTML file, along with your other script tags. You can add the script type text javascript value to the tag too, although it's not necessary

Next, grab the Email.send() function from their homepage as well.


Email.send({
    Host : "smtp.yourisp.com",
    Username : "username",
    Password : "password",
    To : 'them@website.com',
    From : "you@isp.com",
    Subject : "This is the subject",
    Body : "And this is the body"
}).then(
  message => alert(message)
);

Replace the relevant details with the information from your ElasticEmail account. That would be the host, username, and password.

Let's wrap this in a function that we can call inside a click handler. Write a function sendEmail. This assumes you're building a React app and have a way to store values for to, from, subject, and body in state, as well as a success message alert to show the user once the email has been sent.


const {to, setTo} = useState("");
const {from, setFrom} = useState("");
const {subject, setSubject} = useState("");
const {body, setBody} = useState("");

const sendEmail = ({to, from, subject, body}) => {
	Email.send({
    		Host : "smtp.yourisp.com",
    		Username : "username",
    		Password : "password",
    		To : to,
    		From : from,
    		Subject : subject,
    		Body : body
	}).then(
  		message => setSuccessMessage(message)
	);
}

...
<button onClick={sendEmail}>Submit</button>
{!!successMessage && <p>{successMessage}</p>}
...

Conclusion

Being able to send emails from the client-side is important. A contact form is critical for marketing and lead generation, as well as hearing about bug reports and helping customers with problems.

In this tutorial, we explored two different ways of sending emails from a client-side application. Using the mailto link is the easiest way to do it, however, it’s not very robust due to spam and security risks. It also doesn't allow you to add any customization to emails.

The risks of using the mailto link can be mitigated by validating email addresses through a dedicated third-party email validation API like AbstractAPI.

We also looked at using ElasticEmail and SMTPJS.com to run our own SMTP server with ElasticEmail and send emails from the frontend using SMTPJS's easy script src https smtpjs.com tag and a sendEmail function . 

FAQ

Why can’t I send an email using JavaScript?

To send an email, you must use SMTP. SMTP is the protocol that outlines how email traffic is handled. JavaScript apps that run in the browser and on mobile devices are not given access to the ports that the protocol uses. This is done on purpose to prevent attacks from malicious actors and spammers.

What is SMTP?

SMTP (Simple Mail Transfer Protocol) is a set of rules that govern how emails are sent and received. It is similar to HTTP (Hyper Text Transfer Protocol), which controls how webpages and app data should be sent and received. SMTP runs on top of TCP (Transmission Control Protocol), which enables applications to communicate with each other over the web.

How Does SMTP Work?

This is what happens when you send an email from your Gmail account.

  1. You compose an email using the Gmail email client on your device.
  2. You input the recipient’s address (let’s say it’s a yahoo.com address) and click “send.”
  3. Your Gmail client connects to the Gmail SMTP server. Once it receives the email, this email server is now considered an SMTP client.
  4. Your email server communicates with the yahoo.com SMTP server and says it wants to deliver the message. The two servers perform an STMP “handshake.”
  5. The Gmail SMTP client sends your message to the yahoo.com SMTP email server.
  6. The yahoo.com server scans the message and recognizes the domain and the user name.
  7. The yahoo.com mail server receives the email and stores it in the recipient’s mailbox.
  8. When the recipient logs in, their Yahoo email client fetches the new email from the server.


Validate email instantly using Abstract's email verification API.

Get started for free
Validate email instantly using Abstract's email verification API.
Get started