How to Send Email with Node.js
6 mins read

How to Send Email with Node.js

First, let’s start by setting up the HTML form. Open your favorite code editor and create a new HTML file. Inside the file, add the following code:

<form action="/send-email" method="POST">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required>
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>
  <label for="message">Message:</label>
  <textarea id="message" name="message" required></textarea>
  <button type="submit">Send Email</button>
</form>

In the code above, we have created a simple form with three fields: name, email, and message. The form has an action attribute set to “/send-email” and a method attribute set to “POST”. This means that when the user submits the form, the data will be sent to the “/send-email” endpoint using the HTTP POST method.

Now, let’s move on to the Node.js part. Create a new file called “app.js” in the same directory as your HTML file. Open “app.js” in your code editor and add the following code:

const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/send-email', (req, res) => {
  const { name, email, message } = req.body;
  // Create a transporter object using your email service provider's SMTP settings
  const transporter = nodemailer.createTransport({
    host: 'smtp.example.com',
    port: 587,
    secure: false,
    auth: {
      user: 'yo********@ex*****.com',
      pass: 'your-email-password'
    }
  });
  // Configure the email options
  const mailOptions = {
    from: 'yo********@ex*****.com',
    to: 're*******@ex*****.com',
    subject: 'New Contact Form Submission',
    html: `
      

Name:

${name}

Email:

${email}

Message:

${message}

` }; // Send the email transporter.sendMail(mailOptions, (error, info) => { if (error) { console.log(error); res.status(500).send('Error sending email'); } else { console.log('Email sent: ' + info.response); res.send('Email sent successfully'); } }); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });

In the code above, we first import the necessary modules: express, body-parser, and nodemailer. We then create an instance of the Express application and configure it to use the body-parser middleware for parsing form data. This allows us to access the form data sent from the HTML form in the request body.

We define a POST route at “/send-email” that handles the form submission. Inside the route handler, we extract the name, email, and message fields from the request body. We then create a transporter object using the nodemailer module and configure it with your email service provider’s SMTP settings.

Next, we define the email options, including the sender, recipient, subject, and HTML content. We use template literals to dynamically insert the form data into the HTML content.

Finally, we call the sendMail method on the transporter object to send the email. If there is an error, we log it and send a 500 response to the client. If the email is sent successfully, we log the response and send a 200 response to the client.

To run the application, open your terminal or command prompt, navigate to the directory containing the HTML and JavaScript files, and run the following command:

node app.js

You should see the message “Server is running on port 3000” in the console, indicating that the server is running successfully. Now, if you open your web browser and navigate to “http://localhost:3000”, you should see the HTML form. Try submitting the form, and if everything is set up correctly, you should receive an email with the form data.

That’s it! You have successfully set up a “Contact Us” form on your website and implemented the functionality to send form data via email using Node.js. Feel free to customize the form and email content to suit your needs.

Prerequisites

Before we begin, make sure you have the following:

  • Node.js installed on your machine
  • A basic understanding of HTML, CSS, and JavaScript
  • An SMTP server to send emails (e.g., Gmail)

Having Node.js installed on your machine is essential for running JavaScript code outside of a browser environment. It allows you to use JavaScript as a server-side language, which is crucial for building web applications and executing server-side tasks.

If you haven’t installed Node.js yet, you can download it from the official website (https://nodejs.org/) and follow the installation instructions for your operating system.

Additionally, it is important to have a basic understanding of HTML, CSS, and JavaScript. These are the building blocks of web development, and having a solid foundation in these languages will greatly help you in understanding the concepts and techniques discussed throughout this guide.

If you are new to web development or need a refresher, there are many online resources available to learn HTML, CSS, and JavaScript. Websites like Codecademy, MDN Web Docs, and W3Schools offer comprehensive tutorials and interactive exercises to help you get started.

Lastly, you will need an SMTP server to send emails. SMTP stands for Simple Mail Transfer Protocol, and it is the standard protocol used for sending emails over the internet. Most email providers, like Gmail, provide SMTP servers that you can use to send emails from your applications.

If you don’t have an SMTP server set up yet, you can create a Gmail account (if you don’t have one already) and use Gmail’s SMTP server to send emails. Google provides detailed instructions on how to set up SMTP access for your Gmail account, which you can find in their documentation.

Once you have fulfilled these prerequisites, you will be ready to dive into the exciting world of building web applications and sending emails using Node.js!

Now that we have set up the HTML form and added some basic CSS styles to it, let’s take a closer look at the code we just created.
In the HTML file, we start by declaring the document type with the “ tag. Inside the “ section, we set the title of the page to “Contact Us” using the `` tag. We also link an external CSS file named “styles.css” to the HTML file using the “ tag.<br /> Moving on to the “ section, we have a heading ` </p> <h2>` that displays “Contact Us”. This heading provides a clear indication to the user that they are on the contact page.<br /> Below the heading, we have a `</h2> <p>

Leave a Reply

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