As a developer working with Express.js, sending emails is a common requirement that you'll encounter in many applications.
Whether you need to create a professional email template or send bulk email campaigns, Express.js provides powerful features to handle all your email needs.
In this comprehensive guide, I'll explain everything you need to know about sending emails in Express.js applications. We'll explore both SMTP and API-based approaches, complete with working code examples and best practices.
Table of Contents
- How to Send Emails in Express.js
- Prerequisites
- Setting Up an Express.js Server
- Send Emails Via SMTP
- Send Emails Via API
- Troubleshooting Common Errors
- Frequently Asked Questions
How to Send Emails in Express.js
Prerequisites
Below are some requirements you'll need to meet to follow along with this guide:
- Node.js installed on your machine. Download the latest version here
- Code editor (I recommend Visual Studio Code)
- Basic knowledge of JavaScript
- A SendLayer account. You can get started with the trial account that lets you send up to 200 emails for free
Start your free trial at SendLayer
After creating your SendLayer account, make sure to authorize your sending domain. This step is essential to improve your site's email deliverability.
Setting Up an Express.js Server
Before we proceed, I'll show you how to set up a basic server in Express.js so beginners can follow along. However, if you already have a running project, proceed to the sending emails section.
To start, create a new directory for your project:
mkdir send-email
cd send-email
Initialize your project:
npm init -y
This command generates a package.json file with default configurations.
Install Express.js
Install the express package:
npm install express dotenv
The express package sets up the server. I also installed the dotenv package, which allows you to manage sensitive data in a .env file.
After installing express, create a server.js file in the root directory and add the following code:
const express = require('express');
const dotenv = require('dotenv');
dotenv.config(); // Load environment variables
const app = express();
const port = process.env.PORT || 3000;
// Middleware to parse JSON data
app.use(express.json());
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
In the code above, we use the require syntax to import express and the dotenv libraries. The dotenv.config() statement loads environment variables from a .env file.
To start the dev server, run:
node server.js
If everything works well, you'll see:
Server running on port 3000
You can access the server on localhost:3000.
Congrats! You've set up a basic Express.js server. Now, let's proceed to sending emails.
How to Send Emails in Express.js Via SMTP
SMTP (Simple Mail Transfer Protocol) is a standard method for sending emails through mail servers. Using the Nodemailer library, you can send emails through an SMTP server from your Express.js project.
Step 1: Install Nodemailer and Configure .env Variables
Run the command below in your terminal to install nodemailer:
npm install nodemailer
After the installation completes, create a .env file and add the settings for your SMTP server. I'm using SendLayer SMTP for this tutorial, but you can use any SMTP server you like.
SMTP_HOST=smtp.sendlayer.net
SMTP_PORT=587
SMTP_USER=your-smtp-username
SMTP_PASS=your-smtp-password
FROM_EMAIL=sender@example.com
Be sure to replace SMTP_USER and SMTP_PASS with your SMTP user credentials.
If you're using SendLayer, you can access your SMTP credentials from your account dashboard by navigating to Settings » SMTP Credentials.
Note: For SendLayer users, the sender email needs to be at the domain you've authorized. For instance, if you authorized
example.com, your sender email should include@example.com.
Step 2: Create a Route to Send Emails
Now, in the server.js file, add the following code to import the nodemailer module:
const nodemailer = require('nodemailer');
Then we'll create a new function that sends emails. Within the function, we'll initialize a transporter to configure the email options:
const express = require('express');
const dotenv = require('dotenv');
const nodemailer = require('nodemailer');
dotenv.config(); // Load environment variables
const app = express();
const port = process.env.PORT || 3000;
// Middleware to parse JSON data
app.use(express.json());
// Function to send email via SMTP
const sendEmail = async (to, subject, message) => {
try {
// Create a transporter (connection to the email server)
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
secure: false, // false for TLS (587), true for SSL (465)
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
});
// Define the email content
const mailOptions = {
from: process.env.FROM_EMAIL,
to: to,
subject: subject,
text: message,
};
// Send the email
const info = await transporter.sendMail(mailOptions);
console.log('Email sent:', info.messageId);
} catch (error) {
console.error('Error sending email:', error);
throw error;
}
};
// POST route to trigger email
app.post('/send-email', async (req, res) => {
const { to, subject, message } = req.body;
// Validate required fields
if (!subject || !to || !message) {
return res.status(400).json({ status: 'error', message: 'Missing required fields' });
}
await sendEmail(to, subject, message);
res.status(200).json({ status: 'success', message: 'Email sent successfully' });
});
// starting up the server
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Code Breakdown
In the code above, we're creating a function that accepts 3 parameters: to, subject, and message. These parameters correspond to the recipient's email address(es), email subject line, and body of the email.
The nodemailer.createTransport() line of code initializes nodemailer using the SMTP credentials stored in the .env file as parameters. Then we use the transporter.sendMail() function to send the email request.
Notice that I set the to, subject, and text options to correspond to the to, subject, and message parameters the function accepts.
I used the try/catch syntax in JavaScript to implement error handling within the function.
Below the function, I created a new POST endpoint that'll trigger the sendEmail() function. Within this API endpoint, I've specified that it accepts 3 parameters as the request body.
I added a validation to check that all required parameters are specified before sending the request. If one or more of the parameters is missing, the user will encounter a 400 error.
Send Email with Attachments
If you'd like to send emails with attachments, simply add an attachments object to the mailOptions variable:
// Define the email content
const mailOptions = {
from: process.env.FROM_EMAIL,
to: to,
subject: subject,
text: message,
attachments: [
{
filename: 'example.pdf',
path: './path/to/example.pdf' // Update with the correct path to your file
}
]
};
Step 3: Test the SMTP Email
Once you're done, you can test the API you've just created using cURL or an API client like Postman.
Start up the dev server:
node server.js
If you're using Postman, set the request type to POST and enter the post email endpoint, i.e., (localhost:3000/send-email/).
The endpoint requires 3 parameters. If any of the required parameters isn't specified, you'll see an error message.
You'll need to specify the request parameters in the Body tab on Postman. Once done, click the Send button to send your email.
Pro Tip: See Postman's documentation if you need help with sending requests or adding request parameters.
You should receive a success response:
Go ahead and check the recipient's email inbox for the test email you just sent.
To send emails to multiple recipients, simply add the recipient's email addresses to the "to" object in the request parameter, separated by commas.
How to Send Emails in Express.js Via API
Sending emails through an email API is more reliable than using an SMTP server. It also provides advanced features like better email deliverability and scalability for your project.
When handling bulk email campaigns, using an API approach is generally more reliable than SMTP. To learn more about the differences, see our SMTP vs API comparison guide.
Most transactional email service providers like SendLayer include support for sending emails through a secure API. You'll need an API key to interact with their email API.
Start your free trial at SendLayer
To send emails using SendLayer API, you'll need 3 parameters:
-
URL: The API endpoint for sending emails. For SendLayer, this endpoint is
https://console.sendlayer.com/api/v1/email - Headers: Where you'll define the format for the request and authenticate your connection
- Payload: The actual JSON request with details for sending an email like the sender and recipient email address
Pro Tip: To learn more about how SendLayer's API works, check our beginner's guide to using the SendLayer API.
Step 1: Retrieve and Store API Key as Environment Variable
To get your SendLayer API key, log in to your account dashboard. Then, navigate to the Settings » API Keys tab.
Next, click the copy icon below Default API key to copy it.
After that, add the API key as an environment variable to the .env file:
API_KEY=your-sendlayer-api-key
Step 2: Install the SendLayer SDK
You can send your emails by making API requests to the SendLayer email endpoint. However, I'll use the SDK approach because it's easier to implement.
Install the SendLayer Node.js SDK:
npm install sendlayer
Once the installation completes, you're ready to start sending emails in Express.js.
Step 3: Create Email Endpoint
We'll create an endpoint in server.js to handle email requests. Start by importing the SendLayer package:
const { SendLayer } = require('sendlayer');
After that, I'll add a new endpoint to server.js to send an email via the API:
const express = require('express');
const dotenv = require('dotenv');
const { SendLayer } = require('sendlayer');
dotenv.config(); // Load environment variables
const app = express();
const port = process.env.PORT || 3000;
// Middleware to parse JSON data
app.use(express.json());
// POST route to trigger SendLayer API
app.post('/email-api', async (req, res) => {
const { name, to, subject, message } = req.body;
const apiKey = process.env.API_KEY;
const sendlayer = new SendLayer(apiKey);
const payload = {
from: {
name: "Paulie Paloma",
email: process.env.FROM_EMAIL
},
to: [
{
name: name,
email: to
}
],
subject: subject,
html: message,
};
// Validate required fields
if (!subject || !to || !message) {
return res.status(400).json({ status: 'error', message: 'Missing required fields' });
}
try {
const response = await sendlayer.Emails.send(payload);
console.log('Email sent successfully:', response);
res.status(200).json({ status: 'success', message: 'Email sent successfully' });
}
catch (error) {
if (error.response) {
res.status(error.response.status).send({ error: error.response.data });
} else if (error.request) {
res.status(500).send({ error: 'No response from email service' });
} else {
res.status(500).send({ error: 'An error occurred' });
}
}
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Code Breakdown
In the code above, we're creating an Express.js application that implements an email sending service using the SendLayer API.
The application sets up a POST endpoint that accepts four parameters in the request body: name, to, subject, and message. These parameters are used to construct and send an email through SendLayer's API.
The /email-api POST route implements the main email sending functionality. Here's how it works:
- First, we destructure the required parameters from the request body
- Then, initialize the
SendLayerpackage using my API key - Finally, the payload object is written following SendLayer's API requirements
The sendlayer.Emails.send(payload); line makes the actual API call. It accepts a single parameter: the request payload.
The validation check ensures that all required fields (subject, to, and message) are present before proceeding. If any fields are missing, the application returns a 400 status code with an error message.
I also added error handling using a try/catch block with detailed error scenarios:
- 400 for missing required fields
- Status code from API for API-related errors
- 500 for server-side errors
Send Emails to Multiple Recipients
SendLayer API allows you to send emails to multiple recipients, including CC and BCC addresses. We covered all these in a previous tutorial on sending emails in JavaScript via API.
Step 4: Send a Test Email
Once you're done creating your API endpoint, you can proceed to test it on your preferred API client. I'm using Postman for this example.
Save your server.js file and start the server:
node server.js
Once the server is running, open Postman and select the POST method. Enter the endpoint localhost:3000/email-api/.
Then switch to the Body tab and specify the request parameters. Once done, click Send to make the API call.
You should get a success response if everything is properly configured:
Troubleshooting Common Errors
When sending emails in your Express.js project, either through SMTP or an Email API, you might encounter some issues.
Error: Invalid SenderAPIKey
This error indicates the API key you're using to authenticate your connection is invalid. It might occur if you copied the wrong API key or the environment variable isn't reading your API key value from the .env file.
To fix this error, double-check that you've copied the correct API key. Also, check that the logic for retrieving environment variables is properly implemented.
Error: Missing required fields
This error occurs when one or more required parameters aren't provided in the request body. Make sure all required fields (to, subject, message) are included in your API request.
Frequently Asked Questions
These are answers to some of the top questions we see about sending emails from an Express.js application.
How do I send an HTML email in Nodemailer?
To send HTML emails, simply replace text with html in the email data. Then, write your email message using HTML syntax in the html object. Here's an example:
const mailOptions = {
from: 'sender@example.com',
to: 'recipient@example.com',
subject: 'Test HTML Message from Express.js',
html: '<p>This is an <b>HTML template email</b> sent from Express.js using Nodemailer and <a href="https://sendlayer.com">SendLayer SMTP server</a></p>'
};
Can I send emails with attachments in Express.js via API?
Yes! SendLayer's API supports attaching files to emails you send through its email API. For more details, see our beginner's guide to sending emails in JavaScript via API.
What's the difference between SMTP and API for sending emails?
SMTP is the traditional protocol for sending emails, while APIs provide a more modern approach with better reliability, scalability, and features. APIs typically offer faster delivery, better error handling, and detailed analytics. For detailed comparison, see our SMTP vs API guide.
Wrapping Up
In this comprehensive tutorial, we've explored multiple ways to send emails in Express.js applications.
Have questions or want to share your implementation? Drop a comment below. I'd love to hear how you're handling email in your Express.js projects!
Ready to implement this in your application? Start your free trial at SendLayer and send your first email in minutes.










Top comments (0)