Email Sending App using Node.js and the nodemailer library

ยท

3 min read

Email Sending App using Node.js and the nodemailer library

let's create a step-by-step guide to build an Email Sending App using Node.js and the nodemailer library. This example will use Express for the server.

Step 1: Set Up Your Project

  1. Create a new project folder:

     mkdir email-sending-app
     cd email-sending-app
    
  2. Initialize a new Node.js project:

     npm init -y
    
  3. Install necessary dependencies:

     npm install express nodemailer body-parser
    

Step 2: Create Your Folder Structure

Create the following folder structure:

email-sending-app/
|-- src/
|   |-- routes/
|       |-- index.js
|   |-- app.js
|-- views/
|   |-- index.ejs
|-- server.js

Step 3: Set Up Express Server

In app.js, set up a basic Express server and middleware:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const PORT = process.env.PORT || 3000;

app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');

// Set up routes
const indexRoutes = require('./routes/index');
app.use('/', indexRoutes);

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Step 4: Create Routes

In routes/index.js, set up the routes for your Email Sending App:

const express = require('express');
const nodemailer = require('nodemailer');
const router = express.Router();

router.get('/', (req, res) => {
  res.render('index', { success: null, error: null });
});

router.post('/send-email', async (req, res) => {
  try {
    const { to, subject, text } = req.body;

    // Replace with your email and password or use an app password if using Gmail
    const transporter = nodemailer.createTransport({
      service: 'gmail',
      auth: {
        user: 'your-email@gmail.com',
        pass: 'your-password',
      },
    });

    const mailOptions = {
      from: 'your-email@gmail.com',
      to,
      subject,
      text,
    };

    await transporter.sendMail(mailOptions);

    res.render('index', { success: 'Email sent successfully!', error: null });
  } catch (error) {
    console.error(error);
    res.render('index', { success: null, error: 'Error sending email. Please try again.' });
  }
});

module.exports = router;

Step 5: Create Views

In views/index.ejs, create the template for sending emails:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="/styles/main.css">
  <title>Email Sending App</title>
</head>
<body>
  <h1>Email Sending App</h1>

  <% if (success) { %>
    <div class="success-message"><%= success %></div>
  <% } %>

  <% if (error) { %>
    <div class="error-message"><%= error %></div>
  <% } %>

  <form method="post" action="/send-email">
    <label for="to">To:</label>
    <input type="email" id="to" name="to" required>

    <label for="subject">Subject:</label>
    <input type="text" id="subject" name="subject" required>

    <label for="text">Message:</label>
    <textarea id="text" name="text" required></textarea>

    <button type="submit">Send Email</button>
  </form>
</body>
</html>

Step 6: Create CSS Styles

In public/styles/main.css, add your styles:

body {
  font-family: 'Arial', sans-serif;
  margin: 20px;
}

h1 {
  color: #333;
}

form {
  margin-top: 20px;
}

label {
  display: block;
  margin-bottom: 5px;
}

input,
textarea {
  width: 100%;
  padding: 8px;
  margin-bottom: 10px;
}

button {
  background-color: #007BFF;
  color: #fff;
  border: none;
  padding: 8px;
  cursor: pointer;
}

Step 7: Run Your Application

Start the Express server:

node app.js

Visit http://localhost:3000 in your browser, and you should see your Email Sending App. Enter the recipient's email, subject, and message, then click "Send Email." The app will attempt to send the email using the provided credentials.

Remember to replace 'your-email@gmail.com' and 'your-password' with your actual email and password. Keep in mind that for security reasons, it's recommended to use environment variables to store sensitive information like email credentials.

Did you find this article valuable?

Support Revive Coding by becoming a sponsor. Any amount is appreciated!

ย