DEV Community

Cover image for Sending an Email With React Without a Backend Server
Benjamin Nwokolo
Benjamin Nwokolo

Posted on

Sending an Email With React Without a Backend Server

Introduction

In This Tutorial we are going to learn how to send an email in a React Application Without making use of a backend Language Like PHP , Python , Golang and The Rest of Backend Languages.
For us to be able to send an email in react without a Backend we will be making use of Third party Service Called EmailJS . EmailJS is a service from which we can send Emails Directly From Javascript Without a server Code. EmailJS makes it easily to send an email with javascript and its frameworks

Prerequisities

-Basic Knowledge Of React

-An Email JS Account

-An Email Account

Steps

Step 1

So, To be able to make use of EmailJS in our React App we create a free account on emailjs.com

Image description

After Signing up , Verify your Email and Then Proceed to Login into your emailjs account .

Step 2

We have to also add an email service provider on EmailJS from which emails will be sent from , To create a new service , Click On Email services on Your EmailJS Dashboard ,Click on
Add New Service and choose an email service provider of your choice

Image description

For the sake of this tutorial , we’ll be making use of Gmail as a service provider , So after Selecting the email service of your choice , You Proceed to Connect it with your Gmail Account , To Do That click on "Connect Account" as displayed on the screen .

Image description

After Connecting Your Account Click on "Create Service"

Image description

Step 3

Template Creation , to be able to send emails we are to create a Template for our emails , and to do that we ,Click on "Email Templates"in Other to Create an Email template

Image description

Then , Click on “Create New Template” and You are Directed to this page which is the default template :

Image description

Understanding Variables on The Template

  • from_name : it Refers to Sender of the email.

  • to_name : This Refers to the Receiver of the email. in this case it means the person to whom you are sending the mail to.

  • message : it is the main content of your email.

  • to_email : Refers to email address which the email message is been sent to that is the receivers email address

Here is an Edited template :

Image description

So After editing your template click on “save” in other to save your Template. So we are ready to use this template in our React app.

Step 4

We are Going to Create a Contact Form in React to enable us send an email using template in EmailJS. So Head Over to Your Code Editor and Create a form in react , Here is my code for a Basic contact form :

import { useRef } from "react";

const Email = () => {

    const form = useRef();

return (
    <div class="form">
          <div class="title">Contact Us</div>
     <form  ref={form} >

        <div class="input-container ic1">
          <input id="firstname" className="input" type="text" placeholder="Username "  name="to_name"/>
        </div>

        <div class="input-container ic2">
          <input id="email" className="input" type="text" placeholder="Email Address  "  name="from_name"/>
        </div>

        <div class="input-container ic2">
         <textarea  required placeholder="Message"  name="message"></textarea>
        </div>
        <button type="text" className="submit">Submit Message</button>
     </form>
 </div>
   );
}

export default Email;
Enter fullscreen mode Exit fullscreen mode

And Here is The CSS Style For This Particular Contact Form , But You can Create your own unique CSS style When Creating Yours .

*{
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  align-items: center;

  display: flex;
  justify-content: center;
  height: 100vh;
}

.form {
  background-color: black;
  border-radius: 20px;
  box-sizing: border-box;
  height: 600px;
  padding: 20px;
  width: 400px;
}

.title {
  color: #eee;
 margin-left: 60px;
  font-size: 40px;
  font-weight: 600;
  margin-top: 30px;
}


.input-container {
  height: 50px;
  position: relative;
  width: 100%;
}

.ic1 {
  margin-top: 40px;
}

.ic2 {
  margin-top: 30px;
}

.input {
  background-color:white;
  border-radius: 12px;
  border: 0;
  box-sizing: border-box;
  color: black;
  font-size: 18px;
  height: 100%;
  outline: 0;
  padding: 4px 20px 0;
  width: 100%;
}
textarea{
  background-color:white;
  border-radius: 12px;
  border: 0;
  box-sizing: border-box;
  color: black;
  font-size: 18px;
  height: 120px;
  outline: 0;

  width: 100%;
  padding-bottom: 30px;
}

 form label{
     color: white;
     background-color: white;
}

.submit {
  background-color: #08d;
  border-radius: 12px;
  border: 0;
  box-sizing: border-box;
  color: #eee;
  cursor: pointer;
  font-size: 18px;
  height: 50px;
  margin-top: 100px;
 outline: 0;
  text-align: center;
  width: 100%;
}

.submit:active {
  background-color: #06b;
}
textarea::placeholder{
  padding: 30px;
  font-size: 20px;

}
Enter fullscreen mode Exit fullscreen mode

Here is the Form Displayed in The Browser:

Image description

So now, We are to add functionality to this form to enable us send emails using react .

Step 5

Now , Head over to EmailJS Documentation to see how to make use of EmailJs in a React Application by making use of an already made React Code snippets. From the Documentation this is How to make use of EmailJS in A React Application using this function :

import React, { useRef } from 'react';
import emailjs from '@emailjs/browser';

export const ContactUs = () => {
  const form = useRef();

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

    emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', form.current, 'YOUR_PUBLIC_KEY')
      .then((result) => {
          console.log(result.text);
      }, (error) => {
          console.log(error.text);
      });
  };
Enter fullscreen mode Exit fullscreen mode

To make use Of EmailJS in a React App you are to install and import emailjs into your app.

Installing EmailJS

  • To be able to install emailjs Headover to new terminal window , check directory into the root directory of your project and code:
npm  install @emailjs/browser
Enter fullscreen mode Exit fullscreen mode

Image description

After installing EmailJS , Go to The Component which contains your form and Import EmailJS :

import emailjs from '@emailjs/browser';
Enter fullscreen mode Exit fullscreen mode

Step 6

We make use of The function From EmailJS Docs in the component Containing the contact Form

import { useRef } from "react";
import emailjs from '@emailjs/browser';

const Email = () => {

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

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

return (
    <div class="form">
          <div class="title">Contact Us</div>
     <form  ref={form} onSubmit ={sendEmail}>

        <div class="input-container ic1">
          <input id="firstname" className="input" type="text" placeholder="Username "  name="to_name"/>
        </div>

        <div class="input-container ic2">
          <input id="email" className="input" type="text" placeholder="Email Address  "  name="from_name"/>
        </div>

        <div class="input-container ic2">
         <textarea  required placeholder="Message"  name="message"></textarea>
        </div>
        <button type="text" className="submit">Submit Message</button>
     </form>
 </div>
   );
}

export default Email;
Enter fullscreen mode Exit fullscreen mode

We are calling the sendEmail function when the form is been Submitted(onSubmit). From This Function, The sendFormMethod
in the function has Some parameters which are in our EmailJs Account which is Required To Enable us Send an Email Successfully

emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', form.current, 'YOUR_PUBLIC_KEY')
Enter fullscreen mode Exit fullscreen mode

YOUR_SERVICE_ID : To Get Your Service ID Head Over To Email Services on Your EmailJS Account Dashboard

Image description
Copy the Service ID and Replace it with the YOUR_SERVICE_ID parameter in the function

YOUR_TEMPLATE_ID : To Get Your Template ID Head Over To Email Templates on Your EmailJs Account Dashboard

Image description
Copy the Template ID and Replace it with the YOUR_TEMPLATE_ID parameter in the function.

YOUR_PUBLIC_KEY : To Get Your Public Key Head Over To Account on Your EmailJs Account Dashboard.

Image description

Copy the Public Key and Replace it With YOUR_PUBLIC_KEY Parameter in the function.

After Replacing the values with all the necessary parameters from Your Personal EmailJs Account , Here is how the function should be :

import { useRef } from "react"
import emailjs from '@emailjs/browser';

const Email = () => {

const form = useRef();

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

  emailjs.sendForm('service_yta11dh', 'template_2c9a1n9', form.current, 'vnX3YDUTUw7Cj3l_q')
    .then((result) => {
        console.log(result.text);
    }, (error) => {
        console.log(error.text);
    });
    e.target.reset();
};

    return ( 
        <div class="form">
        <div class="title">Contact Us</div>

         <form  ref={form}
         onSubmit ={sendEmail}>

        <div class="input-container ic1">
          <input id="firstname" className="input" type="text" placeholder="Username "  name="to_name"/>

        </div>

        <div class="input-container ic2">
          <input id="email" className="input" type="text" placeholder="Email Address  "  name="from_name"/>
        </div>

        <div class="input-container ic2">
        <textarea  required placeholder="Message"  name="message"></textarea>
        </div>
        <button type="text" className="submit">Submit Message</button>

        </form>
      </div>

     );
}

export default Email;
Enter fullscreen mode Exit fullscreen mode

Note:

  • e.target.reset() in The function is to Clear the Form after it is been submitted.

  • The name Attribute in the input element
    of the form Must Be The Same With name of The Variable in Your EmailJS Template.

Step 7

Now , We can Now Proceed to Send an email from the Browser Using the Form.

Image description

After submitting the form , The Email is sent immediately, Here is my mail sent successfully :

Image description

Conclusion

And there you have it , the email has been sent successfully to my Gmail account, So that is how to send an email in ReactJS without a backend Server using EmailJS.

Top comments (1)

Collapse
 
ahsandev2019 profile image
ahsandev2019

Remember the security issue, don't store your key at frontend