Node.js Tutorial: How to Send Emails with Nodemailer
Tags: javascript, beginners, tutorial, codenewbie
Published: 2023-08-04 13:18:37

Creating a Node.js Contact Form with Nodemailer and Hotmail
Introduction
In this tutorial, we will create a simple contact form using Node.js and Nodemailer https://nodemailer.com/about/, with Hotmail as our email service. The goal is to allow users to fill out a form on your website, and receive an email notification with the contents of the form. This is a great feature for any website, as it provides an easy way for users to get in touch with you directly from the site.

Step 1: Setting Up the Environment
First, we need to install Node.js and npm (which is installed automatically with Node.js). You can download Node.js here https://nodejs.org/en/docs/guides and follow the installation instructions provided.

Step 2: Installing Required Packages
After setting up Node.js, we need to initialize a new Node.js project. In the terminal, navigate to your project directory and run `npm init -y` 
to create a new project. Now, we need to install the required packages:
`npm install express nodemailer cors body-parser dotenv`
Here's what each package does:
`express:` Fast, unopinionated, minimalist web framework for Node.js.
`nodemailer`: A module for Node.js to send emails.
`cors`: A Node.js package for providing a Connect/Express middleware that can be used to enable CORS (Cross-origin resource sharing) with various options.
`body-parser`: Parse incoming request bodies in a middleware before your handlers, available under the req.body property.
`dotenv`: Zero-dependency module that loads environment variables from a .env file into process.env.
Step 3: Setting Up the Express.js Server
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. 

Let's set up a basic Express server:

```
const express = require('express');
const app = express();
const port = 3000;

app.listen(port, () => {
  console.log(`Server started on port ${port}`);
});
```


Step 4: Implementing Nodemailer
Next, we'll implement Nodemailer. This tool allows us to send emails from our Node.js server. Here's how to configure Nodemailer with Hotmail settings:

```
const nodemailer = require('nodemailer');
let transporter = nodemailer.createTransport({
    service: 'hotmail',
    auth: {
      user: 'your-email@hotmail.com',
      pass: 'your-password'
    },
});
```

Step 5: Creating the POST Route
Now, let's create a POST route for '/send', which we will use to send emails. We use body-parser to parse the request body and obtain form data:

```

const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/send', (req, res) => {
  let mailOptions = {
    from: 'your-email@hotmail.com',
    to: 'your-email@hotmail.com',
    subject: 'Contact form submission',
    text: `Name: ${req.body.name}, Email: ${req.body.email}, Message: ${req.body.message}`,
  };

  transporter.sendMail(mailOptions, (err, data) => {
    if (err) {
      res.send('error' + JSON.stringify(err));
    } else {
      res.send('success');
    }
  });
});
```

Step 6: Implementing the Contact Form
On your client-side, create an HTML form and use AJAX to send a POST request to your '/send' route:

```
<form id="contact-form">
  <input type="text" id="name" placeholder="Your name">
  <input type="email" id="email" placeholder="Your email">
  <textarea id="message" placeholder="Message"></textarea>
  <button type="submit">Send</button>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
  $("#contact-form").on('submit', function(e) {
    e.preventDefault();
    var data = {
      name: $("#name").val(),
      email: $("#email").val(),
      message: $("#message").val()
    };
    $.ajax({
      url: 'http://localhost:3000/send',
      type: 'POST',
      data: data,
      success: function(data) {
        alert('Email sent!');
      },
      error: function() {
        alert('An error occurred.');
      }
    });
  });
</script>
```

Step 7: Handling Environment Variables
For security reasons, you should never store sensitive information, like your email and password, directly in your code. Instead, use environment variables. The dotenv package loads environment variables from a .env file into process.env. In your project root, create a .env file and include your email and password:

```
EMAIL=your-email@hotmail.com
PASSWORD=your-password
```

In your Node.js file, require dotenv at the top and use process.env to access your environment variables:

```
require('dotenv').config();

let transporter = nodemailer.createTransport({
    service: 'hotmail',
    auth: {
      user: process.env.EMAIL,
      pass: process.env.PASSWORD
    },
});
```

Conclusion
Congratulations! You've successfully created a contact form using Node.js and Nodemailer, with Hotmail as your email service. If you have any questions or comments, please don't hesitate to leave them below.