Sending emails programmatically is a common requirement in many applications, especially for user notifications, order confirmations, password resets, and newsletters.
Features of Email App
Create a simple application that allows you to send emails using NodeJS. The application will feature:
- Sending plain text and HTML emails.
- Sending emails with attachments.
- Customizing the sender, recipient, subject, and body of the email.
Approach
Below are the steps to follow for building an email-sending system using NodeJS
- Install Nodemailer: Nodemailer is the main module we will use to send emails.
- Create an Email Sending Route: Define a route to handle the email-sending process.
- Set Up SMTP Service: We'll use an SMTP (Simple Mail Transfer Protocol) service for sending emails.
- Handle Email Input: Capture user input (like recipient, subject, and message) using the body parser.
- Send the Email: Use Nodemailer to send the email.
Steps to Build the Email Sending System
Build the email sender by following these steps:
Step 1: Create a Project Folder
Open your terminal (Command Prompt/PowerShell) and run the following commands
mkdir email-sending-system
cd email-sending-systemStep 2: Initialize a NodeJS Project
Run the following command to create a package.json file
npm init -yStep 3: Install Dependencies
Run the following command to install the required dependencies
npm install express nodemailer body-parserThis installs
- Express: Backend framework to handle routing.
- Nodemailer: Module for sending emails.
- Body-parser: Middleware to handle form submissions.
Step 4: Create Server File
Create a file named app.js and require the necessary modules. Then, create an Express instance and set up body-parser to capture form data.
const express = require('express');
const nodemailer = require('nodemailer');
const bodyParser = require('body-parser');
const app = express();
const PORT = 3000;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.render('home');
});
// Handle email sending
app.post('/send-email', (req, res) => {
const { recipient, subject, message } = req.body;
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your gmail',
pass: 'your password'
}
});
// Define the email options
const mailOptions = {
from: 'sender mail',
to: recipient,
subject: subject,
text: message,
};
// Send the email
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error("Error occurred:", error);
res.status(500).send('Error in sending email. Please try again later.');
} else {
console.log('Email sent:', info.response);
res.send('Email sent successfully!');
}
});
});
app.listen(PORT, () => {
console.log(`App is running on port ${PORT}`);
});
- Express Setup: Uses Express to handle HTTP requests and route them.
- Nodemailer: Sends emails via Nodemailer using Gmail's SMTP service.
- Body-Parser Middleware: Body-parser parses form data from POST requests.
- EJS for Dynamic Pages: EJS is used to render HTML templates dynamically with form input.
- Form Submission and Error Handling: Manages form data, sends emails, and displays success or error messages.
Step 5: Enable an App Password in Gmail
- Enable 2-Step Verification (2FA) in your Google Account settings.
- Go to Security > App Passwords and sign in if prompted.
- Select Other (Custom name) and enter a name (e.g., NodeMailer App).
- Google generates a 16-character App Password.
- Copy and use this password in your Node.js application.
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your-email@gmail.com',
pass: 'your-app-password'
}
});
Step 6: Create the Home Page (home.ejs)
Create a views folder in your root directory, and inside it, create a file called home.ejs. Inside views/home.ejs, add the following code
<html>
<body>
<h1>Send Email</h1>
<form action="/send-email" method="POST">
<label for="recipient">Recipient:</label>
<input type="email" name="recipient" id="recipient" required><br>
<label for="subject">Subject:</label>
<input type="text" name="subject" id="subject" required><br>
<label for="message">Message:</label><br>
<textarea name="message" id="message" rows="5" cols="50" required></textarea><br>
<button type="submit">Send Email</button>
</form>
</body>
</html>
Output:
node app.js