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-system Step 2: Initialize a NodeJS Project Run the following command to create a package.json file
npm init -y Step 3: Install Dependencies Run the following command to install the required dependencies
npm install express nodemailer body-parser This 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.
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
Output:
node app.js