DEV Community

Cover image for How to build an SMTP email server for your React App
cesaruseche18
cesaruseche18

Posted on

How to build an SMTP email server for your React App

Today, I want to share a small tutorial about how to create an email server using express that will work with your React app.

First, we will start with getting all the dependencies that we need to build the email server using ExpressJs.

  • Express: Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. APIs.

  • Nodemailer: Nodemailer is a module for Node.js applications to allow easy as cake email sending.

  • dotenv: dotenv is a zero-dependency module that loads environment variables from a .env file into process.env.

  • Body Parser: Node.js body parsing middleware.

  • Cors: CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.

Inside your email server directory run the following on your terminal

npm install express nodemailer dotenv cors body-parser
Enter fullscreen mode Exit fullscreen mode

Now let's start building the server establishing all the required dependencies for the server.

require('dotenv').config()

// routes.js
const router = require('express').Router()
const path = require('path')
const bodyParser = require("body-parser")
const nodemailer = require('nodemailer')
Enter fullscreen mode Exit fullscreen mode

Then, we will create our server using cors, and that it will run on port 5000.

app.use(cors())
app.use(express.json())
app.use("/", router)
app.listen(5000, () => console.log("Server Running"))
Enter fullscreen mode Exit fullscreen mode

Next, we will set up the authentication using our Gmail account credentials, it is really important that you remember .env file in the root directory instead of the current location.

const contactEmail = {
    //this is the authentication for sending email.
host: 'smtp.gmail.com',
port: 465,
secure: true, // use TLS
//create a .env file and define the process.env variables 
    with the credentials you want to use for your email server.
auth: {
    user: process.env.SMTP_TO_EMAIL,
    pass: process.env.SMTP_TO_PASSWORD,
},
}

const contactEmail = nodemailer.createTransport(contactEmail)
    transporter.verify((error, success) => {
if (error) {
    //if error happened code ends here
    console.error(error)
} else {
    //this means success
    console.log('Ready to send mail!')
}
})

Enter fullscreen mode Exit fullscreen mode

Now lets build the API. We are also defining the schema for our JSON object (email).

Also, we are telling Nodemailer about the form data it will be receiving from the front-end and how it should translate said data into a structured email.

router.post("/contact", (req, res) => {
  from: process.env.SMTP_FROM_EMAIL,
    to: process.env.SMTP_TO_EMAIL,
    subject: 'New Contact Form Submission',
    text: `
      from:
      ${req.body.name}

      contact details
      email: ${req.body.email}
      phone: ${req.body.tel}

      message:
      ${req.body.message}`,
    }
contactEmail.sendMail(mail, error => {
    if (error) {
      res.json({ status: "ERROR" })
    } else {
      res.json({ status: "Message Sent" })
    }
Enter fullscreen mode Exit fullscreen mode

Finally, we will connect the backend server with the React front end contact form component.

const ContactForm = () => {
const handleSubmitForm = async e => {
    e.preventDefault()
    setStatus("Sending...")
    const { name, email, phone, message } = e.target.elements
    let details = {
      name: name.value,
      email: email.value,
      phone: phone.value,
    }
    let response = await fetch("http://localhost:5000/contact", {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=utf-8",
      },
      body: JSON.stringify(details),
    })
return (
    <>
       <form
          onSubmit={handleSubmitForm}
        >
        <input type="text" name="name" placeholder="Full Name" />
        <input type="email" name="email" placeholder="Email"/>
        <input type="phone" name="phone" placeholder="Phone number"/>
      </form>
   </>
)
}

Enter fullscreen mode Exit fullscreen mode

I hope you can find this tutorial really helpful, please let me know if you have any questions, I would love to help!

Follow me on Github & Connect with me on LinkedIn

https://github.com/cesareuseche
https://www.linkedin.com/in/cesar-useche-profile/

Top comments (0)