React: Send Email From Your App Without a Backend

Last Updated Jun 20, 2022
Elizabeth (Lizzie) Shipton

Lizzie is a Full Stack Engineer at Udacity and freelance technical content writer. She has experience working with Node, GraphQL, Postgres, React and Sass.

Table of Contents:

There are many reasons you might need to send an email from your React application. A contact form is pretty much a requirement for any progressive web app or website these days. Users need a way to communicate with site admins, and new clients need to be able to get in touch with questions or requests. 

Even if you don’t need a contact form for new clients or questions, etc. having some way for users to submit problems or bug reports is always a good idea.

There are a few ways to send an email from your react application. This article will look at two of those methods: using the mailto HTML attribute, and using EmailJS. These methods will both work for frontend-only applications that are not supported by a backend server. 

Reactjs serverless architecture example

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

SMTP and Why You Need an Email Server

SMTP (or Simple Mail Transfer Protocol) is the communication layer that handles email. Just as HTTP (Hyper Text Transfer Protocol) handles sending and receiving webpages and other website and app-related data, SMTP handles sending and receiving emails.

An SMTP server handles SMTP traffic. One of the important reasons we let SMTP servers handle email is to prevent spam and provide a secure environment for handling sensitive personal information like email addresses. 

An SMTP server works in the following way:

  1. It receives the email information from the client (usually on Port 25.) 
  2. It breaks the email address of both sender and recipient into two pieces: the name and the domain. 
  3. For example, if the email is abstractapi@gmail.com, the name would be abstractapi and the domain would be gmail.com
  4. It examines the domain of the sender and the domain of the recipient. If they both belong to the same domain (i.e. gmail.com) it uses a sending agent to send the email via that domain’s preferred method.
  5. If the domain of the sender and recipient are different, the SMTP server first checks whether the sender’s email address is an active and valid email. This is to prevent spam.
  6. If the sender’s address is active, the SMTP server hands over the email data to the recipient’s SMTP server. That SMTP server then handles delivering the email.

If you are running your own server, via Node or some other backend, you can configure your own SMTP server and send an email that way. Send the email data to your server using a regular AJAX request, then let the server take over and handle sending the email.

Javascript that runs in the browser, however, doesn’t have access to Port 25. This is done specifically to prevent Javascript apps from being able to send spam emails. If you are running a serverless frontend app like a Gatsby or other static React application, you will need to transfer your email data to an SMTP server.

Send Emails in a React App Using Mailto

The mailto link is an href redirect that can be added to the <a> anchor element. It works similarly to a regular href link, but instead of opening a link, it opens an email client on the user’s device. It’s the simplest way to send an email from a frontend app.

To use the mailto redirect, just add it to an anchor element like so:


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

Put the email address that you want to receive the email after mailto:

That’s all it takes to open the user’s default email client on their machine and populate the “recipient” field with the intended email.

Mailto also lets you define 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>

You can use string interpolation to add dynamic content.


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

Easy right? Unfortunately, this comes with a few caveats. First of all, the emails you can send using this method are pretty limited and ugly. At best, you can get a string with some dynamically injected content. 

Next, on mobile, mailto will only work if the user has an email client installed on their device. If the user has multiple email clients installed, it will open the device default without giving the user an option to choose. 

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

For these reasons, mailto, while super quick and easy, isn’t necessarily the best solution for your website contact.

Validate Emails Using AbstractAPI

One additional step you could take to make the mailto redirect more secure would be to validate the sending and receiving email addresses using 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 checks the given email against databases and provides information about whether the address is active, whether the address can be delivered to, whether the address is a free or disposable email address, and whether it is SMTP valid.

Let’s take a look at adding an email validation step to your React 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. Once you’ve signed up, you’ll land on the API’s dashboard, where you’ll see your API key.

Use Your API Key to Send a Request to the API

We’ll use Fetch to send a GET request to the AbstractAPI endpoint with our email for validation. 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"
  }
}

Now, we can decide whether or not to use the email address in our mailto link based on one of these parameters, 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;
       }
   }

Send Emails in a React App Using EmailJS

A better solution is to use a third-party SMTP library like EmailJS. EmailJS is a package that handles the SMTP server part of email sending for you, including any spam or security concerns. They also allow you to create email templates that will send beautiful, high-quality emails.

For the purposes of this tutorial, we’ll assume you already have a basic app spun up using something like Create React App. If you don't know how to do that, go ahead and check out the Create React App docs to get started.

Sign Up for An EmailJS Account

You can sign up for an EmailJS account for free, and you can use the service for free for up to 200 emails a month. You also get two free templates.

Click the “Sign Up” button in the top right corner of the site’s homepage. You’ll be asked to input your name and email address, and will go through an email confirmation process. Once you’ve logged in, you should land on your dashboard.

Add an Email Service

You’ll need to hook up an email service like Gmail, Yahoo, Outlook, etc. You can add multiple services. For now, choose the email service for whichever email address you’d like to receive the mail that you will send from your app. 

Click “Add Email Service.” You’ll get a popup asking you to choose a service.

For this tutorial, we’ll choose Gmail, but the steps are the same for all services. 

You’ll see another popup showing you your new Service ID number. Don’t touch that—we will use it later in the Javascript code. Click “Connect Account.” You’ll be taken through whatever login process your chosen service has. 

Choose the email address that you want to receive the emails. Check the “Send Email on Your Behalf” permissions option. In the EmailJS popup, check “Send test email to verify.” Make sure you receive an email from EmailJS at your chosen address.

Create an Email Template

Navigate to “Email Templates” and click “Create Template.”

You can customize the email template to your heart’s content, adding images, HTML, GIFs, etc. EmailJS allows you to add dynamic content through the {{ handlebars }} syntax. If you add any additional variables or modify the variable names, make a note because you will need to match them in the Javascript code.

Hit “Save” in the top right corner to save the email template.

Install the EmailJS SDK Into Your App


$ npm install --save email-js

or 


$ yarn add email-js

Use the .sendForm Function to Send an Email

The EmailJS SDK provides two methods for sending emails from React. Those are emailjs.send() and emailjs.sendForm(). We’ll use sendForm as it allows us to capture all the data in our contact form. 


import React, { useRef } from 'react';
import emailjs from '@emailjs/browser';
 
const EmailContactForm = () => {
 const form = useRef();
 
 const sendEmail = (e) => {
   e.preventDefault(); // prevents the page from reloading when you hit “Send”
 
   emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', form.current, 'YOUR_PUBLIC_KEY')
     .then((result) => {
         // show the user a success message
     }, (error) => {
         // show the user an error
     });
 };
 
 return (
   <form ref={form} onSubmit={sendEmail}>
     <label>Name</label>
     <input type="text" name="user_name" />
     <label>Email</label>
     <input type="email" name="user_email" />
     <label>Message</label>
     <textarea name="message" />
     <input type="submit" value="Send" />
   </form>
 );
};
 
export default EmailContactForm;
 

Replace  YOUR_SERVICE_ID, YOUR_TEMPLATE_ID, and YOUR_PUBLIC_KEY with the actual values in your EmailJS dashboard. Those can be found in the email services, email templates, and account pages.

We used the useRef hook to grab a reference to the <form> element. EmailJS does some pretty awesome magic to grab all the values from the form and inject them into your template. Just make sure that the variable names you use in the name props on the form inputs match those in your template.

Conclusion

A contact form is a crucial part of your website. In this tutorial we explored two different ways of sending emails from a React application without a backend. Using the mailto link is certainly the easiest option, however, it’s not always advised due to the lack of customization you can make to emails, and some spam and security risks.

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 EmailJS to send templated emails through their SMTP server. 

FAQ

Why can’t I send an email using JavaScript?

To send an email, you must use SMTP. Unfortunately, JavaScript apps that run in the browser and on mobile devices do not have access to the ports that this protocol uses. This is done purposefully to prevent malicious actors from writing apps that can spam users or create other security risks.

What is SMTP?

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

How Does SMTP Work?

These are the steps that happen when you send an email from your Gmail account.

  1. You compose an email using the Gmail email client.
  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 SMTP 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 SMTP server.

Abstract's Email Validation and Verification API comes with libraries, code snippets, guides, and more.

Get started for free
Abstract's Email Validation and Verification API comes with libraries, code snippets, guides, and more.
Get started