How to Send Emails with Node.js and Nodemailer – Tutorial by Mailtrap
Sending emails in Node.js is a common task for many developers. Whether you want to send automatic notifications, newsletters, order confirmations, or any other type of message, Node.js offers a powerful feature set for handling email communications. In this tutorial, we will show you how to use Nodemailer, a popular email sending library, and Mailtrap, an email testing tool, to send emails with Node.js.
Getting Started
First, you’ll need to have Node.js and NPM (Node Package Manager) installed on your machine. You can check if you have them installed by running the following commands in your terminal:
node -v
npm -v
If you don’t have them, you can download and install them from the official Node.js website.
Installing Nodemailer and Mailtrap
Once you have Node.js and NPM installed, you can create a new Node.js project and install Nodemailer using the following commands:
mkdir send-email-tutorial
cd send-email-tutorial
npm init -y
npm install nodemailer
Next, you’ll need to sign up for a Mailtrap account and obtain your SMTP credentials. Once you have your credentials, you can configure Nodemailer to use Mailtrap as your SMTP server. Now, let’s write some code to send an email using Nodemailer:
Sending Emails with Nodemailer
const nodemailer = require('nodemailer');
// Create a transporter using Mailtrap SMTP settings
let transporter = nodemailer.createTransport({
host: 'smtp.mailtrap.io',
port: 2525,
auth: {
user: 'your-mailtrap-username',
pass: 'your-mailtrap-password'
}
});
// Define the email message
let mailOptions = {
from: 'your-email@example.com',
to: 'recipient@example.com',
subject: 'Hello from Nodemailer',
text: 'This is a test email from Nodemailer and Mailtrap!'
};
// Send the email
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
That’s it! You have successfully sent an email using Nodemailer and Mailtrap. You can now use this code as a basis for sending different types of emails in your Node.js applications.
Conclusion
In this tutorial, we’ve shown you how to send emails with Node.js and Nodemailer. We’ve also used Mailtrap as an email testing tool to ensure that our emails are sent and delivered correctly. By following these steps, you can easily integrate email sending capabilities into your Node.js applications. We hope you found this tutorial helpful and informative. Happy coding!
Right to the point. Big appreciated
Hi, I need for Office365 , perfect video 👌👌👌👌
Thanks
Exactly what I needed.. Perfect!!
We, at Mailtrap strive to enrich your knowledge of various technologies. This Node.js tutorial is crafted to guide you on how to send emails using Nodemailer via three methods: SMTP server, Mailtrap Node.js client, and Gmail SMTP server. Did we miss any other Node.js email sending methods you're interested in? Give us a shout in the comments
Thanks