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’s 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 do 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=”YOUR PASSWORD” [Without Quotes].

Configure nodemailer to use our Gmail account

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. Now there are 2 ways to set our SMTP connection details.

a. Set the details like host, port etc ourselves.

b. Use a Nodemailer’s well-known provider like Gmail via the service key in the create transport options object.


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,
  }
});

/* 
  setting service: 'gmail' is same as providing the settings manually in the transport object above.

{
  host: "smtp.gmail.com",
  port: 465,
  secure: true
}

https://github.com/nodemailer/nodemailer/blob/master/lib/well-known/services.json
*/

List of all known providers supported by nodemailer.

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) {
    return Promise.reject(error);
  }
}

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

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

app.post("/contact", 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 UI. So let’s create a static folder that will serve our contact.html inside for 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/contact" 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 the contact form accessible from a browser

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

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

Setup send mail route

app.post('/contact', 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 UI

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

email sent response
Server 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!

2 thoughts on “Contact form with nodemailer in nodejs

Leave a Reply

Back To Top