React: Send Email From Your App Without a Backend

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 [email protected], 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 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:

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.

You can use string interpolation to add dynamic content.

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": "[email protected]",
  "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 

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 (