Build a React App that Sends Emails to Client from Scratch | Step-by-Step Tutorial


Welcome to my website U-GINE MEDIA. In this website I teach tutorials and share source code on some programming (HTML, CSS, JavaScript, React) tutorials. 

Before we get started, do well to subscribe to my channel to never miss out on any update that I post every single day.

You can also visit my GitHub where I upload all the code I have.

In this tutorial topic "Build a React App that Sends Emails to Client from Scratch | Step-by-Step Tutorial", we will learn how to create it following these simple easy steps.

Share this to your programmer friends. If y'all learnt something today, make sure to let me in the comments. 

Get Source Code.

If interested in watching the video before running the code below, you can click the play button to get started.

Setting Up the Project

Before building the "react app" with React.js and CSS, ensure Node.js is installed on your computer. If not, download and install it from the official Node.js website.

Create a Project Folder:

  1. Make a new folder, for instance, “send-email-app”.
  2. Open this folder in your VS Code editor.

Create a Sub Server Folder:

  1. Create a new folder, for instance, "server". 
  2. Initialize the project by opening your terminal and run this command: "npm init -y"
  3. Install the following dependencies: npm i body-parser express nodemon nodemailer dotenv
  4. Run your server


Make an Index Folder:

  1. Create a file, for instance: index.js

Adding Codes:

Add the following code in the index.js file

const express = require("express");
const app = express();
const nodemailer = require("nodemailer");
const bodyParser = require("body-parser");
const dotenv = require("dotenv");
dotenv.config();

//Access-Control-Allow Origin Middleware
//This middleware allows cross-origin requests to your server
app.use((req, res, next) => {
    res.setHeader("Access-Control-Allow-Origin", "*");  
    res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
    next();
})

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


//Gmail SMTP Transporter;
const transporter = nodemailer.createTransport({
    service: "gmail",
    auth: {
        user: process.env.AUTH_EMAIL,
        pass: process.env.AUTH_PASSWORD
    }
})

app.get("/", (req, res) => {
    res.send("Hello World! from server");
})

app.post("/send-email", (req, res) => {
    //Validate request body;
    if(!req.body.email || !req.body.subject || !req.body.text) {
        return res.status(400).send("Missing required fields: email, subject, text");
    }

    //Mail Options
    const mailOptions = {
        from: "Quick Email Form",
        to: req.body.email,
        subject: req.body.subject,
        text: req.body.text
    }

    //Send Mail
    transporter.sendMail(mailOptions, (err, info) => {
        if(err) return res.status(500).send("Error: ", err);
        console.log("Email sent: ", info.response);
        res.status(200).send("Email sent successfully!");
    })
})

app.listen(3000, console.log("Server started on port 3000"));


Create a Sub Client Folder

Initialize the Project:

Open your terminal by pressing Ctrl + J and then use Vite to create a new React app with this command:

  npm create vite@latest ./ -- --template react


Install necessary dependencies and start the development server:

npm install
npm run dev

If your project is running in your browser, congratulations! You’ve successfully set up your weather app. Now, let’s move on to modifying folders and files.

Modify folder and CSS Files:

  1. Remove the default assets folder and App.css file.
  2. Replace the content of index.css with the provided CSS code.

  @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@100;300;400;500;700&display=swap');

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

body {
  font-family: "Poppins", sans-serif;
  font-size: 16px;
  line-height: 1.6;
  background-image: url("./assets/wallpaper.jpg");
  background-size: cover;
  background-position: center;
  min-height: 100vh;
  background-repeat: no-repeat;
  display: flex;
  justify-content: center;
  align-items: center;;
}

.app {
  min-width: 500px;
  width: 90%;
  padding: 30px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 10px;;
}

.app h1 {
  font-size: 2.3rem;
  margin-bottom: 20px;
  text-align: center;
  color: #fff;
}

.app form div {
  margin-bottom: 5px;
}

.app form label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #fff;
}

.app form input,
.app form textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 16px;
  outline: none;
}

.app form button {
  background: #f60000;
  color: #fff;
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  width: 100%;;
}

.popup {
  position: absolute;
  top: 3%;
  right: 2%;
  padding: 4px 10px;
  border-radius: 3px;
  color: #fff;
}

.popup.success {
  background: green;
}

.popup.error {
  background: red;
}
  
  

In App.jsx, add the code.


import React from 'react'
import { useState } from 'react'

const App = () => {
  const [email, setEmail] = useState('');
  const [subject, setSubject] = useState('');
  const [text, setText] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(false);
  const [success, setSuccess] = useState(false);


  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(false);
    setSuccess(false);

    const data = {
      email: email,
      subject: subject, 
      text: text
    }

    const response = await fetch("http://localhost:3000/send-email", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    })

    if(!response.ok) {
      setError(true);
      setLoading(false);
      return;
    }

    const result = await response.text();
    if(result === "Email sent successfully!") {
      setEmail("");
      setSubject("");
      setText("");
      setLoading(false);
      setSuccess(true);
    }

    setTimeout(() => {
      setSuccess(false);
      setError(false)
    }, 5000)
  }

  return (
    <div className='app'>
      <h1>Quick Email Form</h1>
      <form encType='application/x-www-form-urlencoded' method='POST' onSubmit={handleSubmit}>
        <div>
          <label htmlFor='email'>Email:</label>
          <input type='email' id='email' name='email' required onInput={(e) => setEmail(e.target.value)} value={email} />
        </div>
        <div>
          <label htmlFor='subject'>Subject:</label>
          <input type='text' id='subject' name='subject' required onInput={(e) => setSubject(e.target.value)} value={subject} />
        </div>
        <div>
          <label htmlFor='message'>Message:</label>
          <textarea id='message' name='text' rows={5} required onInput={(e) => setText(e.target.value)} value={text}></textarea>
        </div>
        {loading ? <button>Loading...</button> : <button>Submit</button>}
        {success && <div className='popup success'>Email sent successfully</div>}
        {error && <div className='popup error'>Error sending mail</div>}
      </form>
    </div>
  )
}

export default App

Conclusion and Final word

Now, we have reached the end of our code, for any information, you can comment any problem or code-not-working issues to resolve it, am always with you. You can also visit my YouTube Channel for more updates on HTML, CSS & JavaScript Designs. I believe you can create "React App that Sends Emails to Client ". and do so much more with codes. Go extremely far in exploring the world of HTML, CSS & JavaScript, its gonna be fun, trust me 😃.

Keep experimenting! You can add other cool features. Try improving error handling and adding other cool updates to make your chatbot even better.

If you run into any issues, you can download the source code for this AI chatbot project by clicking the “Download” button. Don’t forget to check the README.md file for setup and usage instructions. If you need help, you’ll also find support information there.

Happy Coding Journey 🚀






Post a Comment

0 Comments

Close Menu