Guides
Last Updated Mar 18, 2024

React: Send Email From Your App Without a Backend

Elizabeth (Lizzie) Shipton

Table of Contents:

Get your free
API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required
Get your free
Email Verification API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

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, especially if you don't have a dedicated client management solution.

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

Let’s send your first free
API
Email Verification API
call
See why the best developers build on Abstract
Get your free api

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. Let’s take a look at a couple of the customization options.

Using Variables

EmailJS allows you to add dynamic content through the {{ handlebars }} syntax. These variables can then be named the same way inside your Javascript code. For example:


Hello {{name!}}
Thank you so much for subscribing to the AbstractAPI newsletter. We provide valuable weekly tips and tricks to optimize your workflows.

You can populate this variable with the string pulled from the name field in your React web form by passing it to the .sendForm function we’ll use when we incorporate the EmailJS SDK into our code. More on this in the next section.

Formatting With HTML

EmailJS allows you to format beautiful, custom emails using simple HTML code. You can use the HTML to insert images, headings, links and more. To do this, click the code (<>) button. This will open a source code editor dialogue, into which you can paste your HTML code.

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

Install the EmailJS SDK Into Your App

Next, let’s look at setting up the EmailJS SDK, which is how we’ll get the information out of our React form and pass it to our EmailJS template. The first thing you’ll need to do is install the SDK into your app using the command line.


$ npm install --save email-js

or 


$ yarn add email-js

Use the .sendForm Function to Send an Email

Next, import the EmailJS SDK into your App.js file.


import emailjs from '@emailjs/browser';

The EmailJS SDK provides two methods for sending emails from React. Those are emailjs.send() and emailjs.sendForm().

First, initialize the EmailJS SDK. You can do this inside a useEffect hook so that it happens when the component mounts:


useEffect(() => emailjs.init("YOUR-PUBLIC-KEY-HERE"), []);

Once the SDK is initialized, we’ll use sendForm to capture our user data and inject it into our email, as it allows us to capture all the data in our contact form at once. 


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.

Copy the service ID from the Email Services page:

Grab the template ID from the Email Templates page:

And get the public key from your Accounts page:

In the above example, we used the useRef hook to grab a reference to the <form> element in the JSX code. We then passed that variable into the .sendForm function, where EmailJS is able to parse the form, grab the variables, and inject them into your template.

Make sure the variable names you used in your React code are exactly the same as the ones you used in your EmailJS template.

Other Integrations

SendEmailJS isn’t the only email sending service that integrates with React. Other services include Postmark, Amazon AWS SES, MailerSend, SendGrid, and Nodemailer. Resend also makes a handy React library called React Email that provides a handful of components that can be incrementally imported into your React project to build and send emails directly in React.

Information on getting started with React Email can be found here.

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.

4.7/5 stars (25 votes)

Elizabeth (Lizzie) Shipton
Lizzie Shipton is an adept Full Stack Developer, skilled in JavaScript, React, Node.js, and GraphQL, with a talent for creating scalable, seamless web applications. Her expertise spans both frontend and backend development, ensuring innovative and efficient solutions.
Get your free
Email Verification API
API
key now
Abstract's Email Validation and Verification API comes with libraries, code snippets, guides, and more.
get started for free

Related Articles

Get your free
API
Email Verification API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required