SMTP in Nodejs
Node.js does not have support for working with SMTP in its standard libraries, but fortunately there are a number of third-party libraries for sending emails using SMTP in your Node.js application. Nodemailer is probably the most popular library for sending emails in Node.js and it's what we'll be using in this article.
Prerequisites
- Ensure that you have Node.js installed on your system. Visit the official website for instructions on how to install Node.js on your operating system.
- You have created and verified your domain on AhaSend.
- You have created SMTP credentials (username and password) for authentication.
Sending with the Nodemailer package
First, you need to install Nodemailer
in your Node.js project. Run the following command in your project directory:
npm install nodemailer
Create a new JavaScript file (e.g., sendEmail.js
) and import Nodemailer. Configure it to use the SMTP server with the necessary authentication and TLS settings.
const nodemailer = require('nodemailer');
// Create a transporter object using the SMTP transport
let transporter = nodemailer.createTransport({
host: 'send.ahasend.com',
port: 587,
requireTLS: true, //Force TLS
auth: {
user: 'YOUR_SMTP_USERNAME', // SMTP username
pass: 'YOUR_SMTP_PASSWORD', // SMTP password
},
});
// Email options
let mailOptions = {
from: '"Your Name" <[email protected]>', // sender address
to: '[email protected]', // list of receivers
subject: 'Hello ✔', // Subject line
text: 'Hello world?', // plain text body
html: '<b>Hello world?</b>', // html body
};
// Send email
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
});
[email protected]
, YOUR_SMTP_USERNAME
and YOUR_SMTP_PASSWORD
with an email address from your domain (that is added to your AhaSend account), and your actual SMTP credential username and password.Run your JavaScript file using Node.js to send the email:
node sendEmail.js
Nodemailer
is a powerful library for sending emails in Node.js, supporting a wide range of features from simple plaintext emails to complex messages with HTML content and attachments. This guide covered the basics to get you started. For more advanced features and options, refer to the Nodemailer official documentation.