Sending emails through Nodemailer and Node.js

Email communication plays a crucial role in many web applications, whether it's for user verification, password resets, or transactional emails. In Node.js applications, Nodemailer is a popular library used for sending emails seamlessly. In this article, we'll explore how to set up Nodemailer in a Node.js project and use it to send emails.

The GitHub repository link can be found here

Preparation: Setting Up Express.js Server

Let's start by creating a simple Express.js server:

mkdir nodemailer-express cd nodemailer-express npm init -y npm install express

We use server.js as the entry point:

const express = require('express'); const app = express() const port = 3000 app.get('/', (req, res) => { res.send('API is running'); }); app.listen(port, () => { console.log(`Server is running on port:${port}`) })

Run node server.js and go to http://localhost:3000 in the browser. You should see the message "API is running".

Install Nodemailer and Setup Helper Function

Now install nodemailer using the following command:

npm install nodemailer

Create a file named sendEmail.js in the root directory and paste the following code:

const nodemailer = require('nodemailer'); const transporter = nodemailer.createTransport({ host: "YOUR_SMTP_SERVER_HOST", port: 465, secure: true, auth: { user: "YOUR_EMAIL_ALIAS_FROM_EMAIL_SERVICE_PROVIDER", pass: "YOUR_EMAIL_PASSWORD_FROM_EMAIL_SERVICE_PROVIDER", }, }); const sendEmail = async ({ from, to, subject, text = '', html = '' }) => { try { const info = await transporter.sendMail({ from, to, subject, text, html }); return info; } catch (error) { console.error('Error sending email: ', error); throw new Error('Failed to send email'); } }; module.exports = sendEmail;

Let's break down the codes:

Create a transporter object: This object is created using the createTransport method provided by Nodemailer. We need host information from an SMTP server, as well as user and pass, which are credentials specifically for sending emails through the email service provider.

Define sendEmail Function: This asynchronous function accepts an object as an argument with properties representing email details such as sender, recipient, subject and message body (text and/or HTML), etc. Inside it, an email is sent using the sendMail method from transporter. Once completed, it returns information about the sent email, such as message ID, response from the server, etc.

Define Email API

To create the API endpoint for sending emails, we will need to generate a file named testEmailRoute.js:

const sendEmail = require('./sendEmail.js'); const testEmailRoute = async (req, res) => { try { const sentEmail = await sendEmail({ to: 'RECIPIENT_EMAIL', from: 'SENDER_NAME <SENDER_EMAIL>', subject: 'Your Custom Subject Here', text: "Your custom email body text goes here!", }); if (sentEmail) { res.sendStatus(200); } else { res.sendStatus(500); throw new Error('Email not sent'); } } catch (error) { console.error(error); res.sendStatus(500); } } module.exports = testEmailRoute;

Replace RECIPIENT_EMAIL with the email address you want to send to, and replace SENDER_NAME and SENDER_EMAIL with your name and email address respectively.

Test sending email

Now, include the testEmailRoute in server.js and make a POST request to http://localhost:3000/test-email using either Postman or Thunder Client. You will see your inbox receive a new email.

const testEmailRoute = require('./testEmailRoute.js'); app.post('/test-email', testEmailRoute)

The steps and codes described above are similar to the ones I used for both this portfolio website and this project. Give it a try and let me know what you think!