How To Send Email In React JS

Udemezue John - Oct 12 - - Dev Community

Introduction.

Building a web application often involves adding features like contact forms, notifications, or any other user interactions that require sending emails. If you’ve ever wondered how to handle this in a React app, you're in the right place.

So, how can you send an email from a React application? React, being a frontend framework, doesn’t have built-in email-sending capabilities because it runs in the browser. However, I can still handle this with a few smart tools and workarounds.

In this article, I’ll walk you through the steps to send emails in React using a third-party service like EmailJS, a backend API, and a combination of Node.js with libraries like Nodemailer.

By the end, you'll be ready to add email functionality to your React projects.

Setting the Stage: Can React Send Emails Directly?

React is designed to build user interfaces and handle frontend logic. It can’t interact with an SMTP server (the service that handles emails) because of security restrictions.

Browsers don't allow this level of access to external servers, which is good for security, but it limits direct email sending from React apps.

To work around this limitation, I can either use a backend service (Node.js, for instance) or integrate with third-party services like EmailJS that handle email sending for you.

Method 1: Sending Email Using EmailJS in React.

EmailJS is a popular service that allows you to send emails directly from the frontend without setting up your backend.

This service works by providing a client-side API that interacts with your email provider.

Here’s how to set up EmailJS in your React project:

Step 1: Sign Up and Create a Service in EmailJS

First, create an account at EmailJS.

After signing up, create an email service (for example, Gmail) in the Email Services section.

Next, create an email template that will define the email’s format.

Step 2: Install EmailJS in Your React App

Once the account is ready, install the EmailJS SDK by running:

npm install emailjs-com --save
Enter fullscreen mode Exit fullscreen mode

Step 3: Integrate EmailJS in Your React Component.

In your React component, import EmailJS and set up a simple form:

import React, { useRef } from 'react';
import emailjs from 'emailjs-com';

const ContactForm = () => {
  const form = useRef();

  const sendEmail = (e) => {
    e.preventDefault();

    emailjs.sendForm(
      'YOUR_SERVICE_ID', 
      'YOUR_TEMPLATE_ID', 
      form.current, 
      'YOUR_USER_ID'
    )
    .then((result) => {
        console.log(result.text);
    }, (error) => {
        console.log(error.text);
    });
  };

  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 ContactForm;

Enter fullscreen mode Exit fullscreen mode

Here’s what’s happening:

sendForm() is a method provided by EmailJS that sends the form data to the email service.

Replace 'YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', and 'YOUR_USER_ID' with your actual IDs from your EmailJS account.

Step 4: Test It Out.

Run your app and submit the form. If everything is set up correctly, you'll be able to send an email right from your React application.

Method 2: Sending Emails via Node.js Backend (Nodemailer)

If you’d rather not rely on a third-party service like EmailJS, or if you need more control over your email sending process, another option is to set up a backend server with Node.js and use Nodemailer to send emails.

Step 1: Set Up a Node.js Server

In your project root, create a server.js file and install the necessary packages:

npm install express nodemailer
Enter fullscreen mode Exit fullscreen mode

Step 2: Configure Nodemailer.

In server.js, set up a simple email-sending route:

const express = require('express');
const nodemailer = require('nodemailer');
const cors = require('cors');

const app = express();
app.use(cors());
app.use(express.json());

app.post('/send-email', (req, res) => {
  const { name, email, message } = req.body;

  const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: 'your-email@gmail.com',
      pass: 'your-email-password',
    },
  });

  const mailOptions = {
    from: email,
    to: 'recipient-email@gmail.com',
    subject: `Message from ${name}`,
    text: message,
  };

  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      return res.status(500).send(error.toString());
    }
    res.send('Email sent: ' + info.response);
  });
});

app.listen(5000, () => {
  console.log('Server is running on port 5000');
});
Enter fullscreen mode Exit fullscreen mode

Step 3: Set Up the Frontend to Call Your API.

In your React app, create a form that sends data to your backend:

const handleSubmit = (e) => {
  e.preventDefault();

  fetch('http://localhost:5000/send-email', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      name: e.target.name.value,
      email: e.target.email.value,
      message: e.target.message.value,
    }),
  })
    .then((response) => response.text())
    .then((data) => console.log(data))
    .catch((error) => console.error(error));
};

Enter fullscreen mode Exit fullscreen mode

This method gives you full control over your emails and is perfect if you already have a backend or want to avoid third-party services.

Pros and Cons of Each Approach

Using EmailJS

Pros:

  • No need to set up a backend server.
  • Easy to integrate with React.
  • Handles the email sending for you.

Cons:

Limited free tier (up to 200 emails per month).
Somewhat reliant on a third-party service.

Using Nodemailer (with Node.js)

Pros:

  • Full control over the process.
  • No third-party dependency once you set up your backend.
  • Unlimited emails depending on your email provider.

Cons:

Requires setting up and maintaining a backend.
More complex to implement.

Conclusion.

Sending emails in React is doable, but it requires a bit of a workaround.

Whether you choose a third-party service like EmailJS or prefer to build your own backend using Node.js and Nodemailer, the path you take will depend on your project’s needs.

Are you leaning toward the simplicity of EmailJS or the flexibility of Nodemailer?

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player