Contact form with nodemailer in nodejs

contact-form-with-nodemailer-in-nodejs-thumbnail

In this tutorial, we will be looking at how we can create a contact form with a nodemailer using Gmail as our SMTP server in nodejs. Now for those who aren’t familiar with nodemailer, it’s a nodejs module that we can use in our applications that allows us to easily integrate mailing functionality to our nodejs application. So let’s get started, shall we?

Set up a Gmail account

Please make sure you have a Gmail account ready. Also for our nodejs application to be able to send email using our Gmail account we have to enable Less Secure App.

Install nodemailer and other required nodejs packages

Firstly, we need to initialize our nodejs app using the command below.

npm init -y

Secondly, need to install some dependencies

npm install express nodemailer dotenv

Set environment variables

Lets’ create a “.env” file inside our project’s root directory with the following

  • GMAIL_USER=”YOUR EMAIL” [Without Quotes].
  • PASSWORD=”YOURPASSWORD” [Without Quotes].

Configure nodemailer to use our Gmail account

After that now to make nodemailer understand that we would like to use our Gmail account to send emails we need to create what is known as an SMTP transporter.


And below is the code as to how we do it.

require(dotenv).config()
const nodeMailer = require('nodemailer')

const transporter = await nodeMailer.createTransport({
  service: 'gmail',
  auth: {
    user: process.env.GMAIL_USER,
    pass: process.env.PASSWORD,
  }
});

Create our sendMail function

sendMail function as the name suggests will be responsible send out the email.

require("dotenv").config();
const express = require("express");
const nodeMail = require("nodemailer");
const path = require("path");

const app = express();

app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, "public")));

async function mainMail(name, email, subject, message) {
  const transporter = await nodeMail.createTransport({
    service: "gmail",
    auth: {
      user: process.env.GMAIL_USER,
      pass: process.env.PASSWORD,
    },
  });
  const mailOption = {
    from: process.env.GMAIL_USER,
    to: process.env.EMAIL,
    subject: subject,
    html: `You got a message from 
    Email : ${email}
    Name: ${name}
    Message: ${message}`,
  };
  try {
    await transporter.sendMail(mailOption);
    return Promise.resolve("Message Sent Successfully!");
  } catch (error) {
    console.log(error)
    return Promise.reject(error);
  }
}

app.get("/", (req, res) => {
  res.render(index.html);
});

app.post("/", async (req, res, next) => {
  const { yourname, youremail, yoursubject, yourmessage } = req.body;
  try {
    await mainMail(yourname, youremail, yoursubject, yourmessage);
    
    res.send("Message Successfully Sent!");
  } catch (error) {
    res.send("Message Could not be Sent");
  }
});

app.listen(3000, () => console.log("Server is running!"));

Prepare a contact form to work with nodemailer

We will also need our contact form. So let’s create a static folder that will serve our contact.html inside which you can copy-paste the below code.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Contact</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="contact-section">
      <h1>Contact Us</h1>
      <div class="border"></div>

      <form action="http://localhost:3000/" method="post" class="contact-form">
        <input
          type="text"
          class="contact-form-text"
          placeholder="Your name"
          name="yourname"
          required
        />
        <input
          type="email"
          class="contact-form-text"
          placeholder="Your email"
          name="youremail"
          required
        />
        <input
          type="text"
          class="contact-form-text"
          name="yoursubject"
          placeholder="Subject"
          required
        />
        <textarea
          class="contact-form-message"
          placeholder="Your message"
          name="yourmessage"
        ></textarea>
        <input
          type="submit"
          id="form-submit"
          class="contact-form-btn"
          value="Send"
          required
        />
      </form>
    </div>
  </body>
</html>

Make contact form accessible from browser

Once we have our contact.html ready we need to make our form available to users from their browser. To do this we need to create a get route as below

app.get('/', (req, res) => {
  res.render(contact.html);
});

Setup send mail route

app.post('/', async (req, res, next) => {
  const { yourname, youremail, yoursubject, yourmessage } = req.body;
  try {
    await sendMail(youremail, yoursubject, yourmessage);
  } catch (error) {
    res.send("Message Could not be Sent");
  }
  res.send("Message Succssfully Sent!");
});

Final product

contact-form for nodemailer
Contact-Form

Lastly, we can fill in the form with the required fields and test it in our browser.

Response from the nodemailer
Server’s Response.

Conclusion

Alright! we have successfully created our first contact us form with nodemailer in nodejs.

It was so much fun making this module.

I hope you people find it useful, If you have any queries feel free to ask and share your feedback in the comments below.

THANK YOU!

Leave a Reply

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

Back To Top