Send Emails with Node.js & React Js

Today, I will share with you the logic behind email sending in MERN App. Send Emails with Node.js & React Js.

How to MAKE an Email Send API in Nodejs

We can send emails using Nodejs but for the front-end, we required any front-end technology like VueJs, AnuglarJs, or Reaactjs. So I am using Reactjs for client-side applications. You can use pure HTML too for getting form input.

Email Sending in MERN App

Before going ahead you must disable Gmail Third-Party security otherwise You request will not send from your MERN App to Gmail

How to Re-Authorize for Gmail | Cirrus Insight
Source: www.cirrusinsight.com

You need some packages for running MERN App in your System. You can install React and node from their respective official website.

Lets talk about Front-end part ( React JS )

I am using bootstrap to design the form you can use material UI or normal HTML Form. To Install bootstrap in your react app use the below command.

npm install bootstrap --save

I am using AXIOS for sending React form data to Nodejs. You can use fetch()

npm install axios  

or // using yarn 

yarn add axios

Learn about AXIOS and FETCH – Differences between Axios and fetch

Now We will see Node Part here

In Node js, You will have to install some packages

    "cors": "^2.8.5",
    "express": "^4.17.1",
    "nodemailer": "^6.6.3",
    "path": "^0.12.7"
Installing nodemailer from npm

With the npm CLI: npm install nodemailer

With the yarn CLI: yarn add nodemailer

CORS and Nodemailer both are very important. Without Nodemailer You can not send mail. You must install cors in your node app. cors is important for API otherwise you will get an error in your Front-end app. See the below image of CORS errors.

3 Ways to Fix the CORS Error — and How the Access-Control-Allow-Origin  Header Works | by David Katz | Medium
CORS Error, Image Source – https://medium.com/

Learn more about Nodemailer https://www.w3schools.com/nodejs/nodejs_email.asp

Coding Part :

Now We will see REACT code first here

src/EmailSend.js

import React, { useState } from "react";
import axios from 'axios'

const EmailSend = () => {
 
  const [msg,setMsg] = useState('');
  const [user, setUser] = useState({
    to: "",
    subject: "",
    description: ""
  });

  const { to, subject, description} = user;
  const onInputChange = e => {
    setUser({ ...user, [e.target.name]: e.target.value });
  };

  const onSubmit = async e => {
    e.preventDefault();
    await axios.post("http://localhost:5000/users/",user)
   .then(response => setMsg(response.data.respMesg));
  };
  return (
    <div className="container">
         <h3 className="text-center text-success mb-2 mt-4">Email Send using React and Node </h3>
         <h6 className="text-secondary text-center mb-4 mt-1">By Improve Programming Logic</h6>
      <div class="row">  
     
       <div className="col-sm-4 mx-auto shadow p-5">
        <h4 className="text-center mb-2">Send E Mail </h4>
           <p class="mb-3 mt-2" style={{color:"green",marginLeft:"57px"}}><b>{msg}</b></p>
          <div className="form-group mb-3">
            <input
              type="text"
              className="form-control form-control-lg"
              placeholder="To"
              name="to"
              onChange={onInputChange}
              value={user.to}
            />
          </div>
          <div className="form-group  mb-4 ">
            <input
              type="text"
              className="form-control form-control-lg"
              placeholder="Subject"
              name="subject"
              onChange={onInputChange}
              value={subject}
            />
          </div>
          <div className="form-group  mb-4">
            <textarea
              type="text"
              className="form-control form-control-lg"
              placeholder="Description"
              name="description"
              onChange={onInputChange}
              value={description}
            />
          </div>
         
          <button onClick={onSubmit} className="btn btn-primary btn-block " style={{marginLeft:"100px"}}>Send Mail</button>
      
      </div>
    </div>
  </div>  
  );
};

export default EmailSend;

Now call the EmailSend file in App.js

src/App.js

import React from "react";
import "./App.css";
import "../node_modules/bootstrap/dist/css/bootstrap.css";
import EmailSend from "./EmailSend";

function App(props) {
  return (
      <div className="App">
        <EmailSend />
      </div>
  );
}
export default App;

By default, your react app will run on port number 3000

http://localhost:3000/

But You can change your PORT number in the package.json file using this simple code of line

"scripts": {
    "start": "set PORT= 3005 && react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

Now Nodejs Code starts here

index.js file is my main file you can change its name according to your choice

index.js

const path = require('path');
const express = require('express');

const nodemailer = require('nodemailer');
const app = express();
const cors = require('cors')
app.use(cors())
const buildPath = path.join(__dirname, '..', 'build');
app.use(express.json());
app.use(express.static(buildPath)); 

app.post('/users',(req,res)=>{

    var transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
          user: 'your mail',
          pass: 'password'
        }
    });

    var mailOptions = {
        from: 'your mail',// sender address
        to: req.body.to, // list of receivers
        subject: req.body.subject, // Subject line
        text:req.body.description,
        html: `
        <div style="padding:10px;border-style: ridge">
        <p>You have a new contact request.</p>
        <h3>Contact Details</h3>
        <ul>
            <li>Email: ${req.body.to}</li>
            <li>Subject: ${req.body.subject}</li>
            <li>Message: ${req.body.description}</li>
        </ul>
        `
    };
    
    transporter.sendMail(mailOptions, function(error, info){
        if (error)
        {
          res.json({status: true, respMesg: 'Email Sent Successfully'})
        } 
        else 
        {
          res.json({status: true, respMesg: 'Email Sent Successfully'})
        }
    
      });
});

// listen to the port
app.listen(5000, () => {
    console.log('server start on port 3030');
  });

I am running the Node project on 5000 but you can use a different port.

http://localhost:5000/

For Source Code drop me a mail: dysengg252@gmail.com

See our more projects on MERN App

Theme Color change in React JS

Records display in Material UI Table

Display Records in Model Box in React

Responsive Navbar in Material UI React

Upload PDF file in React, Laravel

Leave a Reply

Your email address will not be published. Required fields are marked *