Learn how to send test emails using Node.js and Mailtrap with a real-world example and step-by-step guide.
October 22, 2025
|
7 min read
Sending emails is a core feature in almost every modern web application. Whether you're building a signup flow, a notification system, or a contact form, email functionality is essential.
In this tutorial, we'll explore how to send emails using Node.js with the help of Mailtrap-a developer-friendly tool for testing and sending emails.
Note: This guide assumes you have some basic knowledge of Node.js and NPM. If you're new to Node, check out this beginner guide to Node.js.
Mailtrap is a complete email delivery platform built for developers. It offers two main services:
First, initialize a Node project:
Then install Nodemailer, the popular Node.js library for sending emails:
These are for the sandbox environment. If you want to send real emails, go to Email Sending and generate production credentials instead.
Create a file named sendEmail.js:
const nodemailer = require("nodemailer"); // Replace with your Mailtrap credentials (testing or production) const transporter = nodemailer.createTransport({ host: "smtp.mailtrap.io", // Use send.mailtrap.io for production sending port: 587, auth: { user: "your_mailtrap_username", pass: "your_mailtrap_password", }, }); const mailOptions = { from: '"Node Mailer" <from@example.com>', to: "to@example.com", subject: "Test Email from Node.js", text: "This is a plain text body", html: "<h1>This is an HTML body</h1>", }; transporter.sendMail(mailOptions, (error, info) => { if (error) { return console.log("Error:", error); } console.log("Email sent successfully!", info.messageId); });
Replace the credentials with either your sandbox or production Mailtrap details, depending on your use case.
You should see:
If you're using the sandbox, the email will appear in your Mailtrap inbox. For production, the message will be delivered to the recipient's real inbox.
You can customize:
| Issue | Fix |
|---|---|
| `ECONNECTION` error | Check if you're behind a VPN or firewall |
| Auth failed | Double-check your Mailtrap credentials |
| Timeout | Try using port 2525 instead of 587 |
Mailtrap isn't just for testing - it's a full-stack solution for handling email in development and production.
If you prefer working with APIs instead of SMTP, Mailtrap also offers a powerful Email Sending API.
Let me know if you'd like an example using Mailtrap's Email API instead of Nodemailer - happy to include that too!