How to send an email with Node.js

Sending emails is a common feature in web applications. Node.js offers several libraries to simplify the process, such as nodemailer. In this article, we will see how to configure and use nodemailer to send emails.

Installing Nodemailer

First, we need to install nodemailer. Run the following command in your terminal:

npm install nodemailer

Basic Configuration

Once nodemailer is installed, we can configure a transporter to send emails. Here is an example:

const nodemailer = require('nodemailer');

const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'youremail@gmail.com',
    pass: 'yourpassword',
  },
});

Note: It is important not to expose credentials directly in the code. Use environment variables for better security.

Sending an Email

With the transporter configured, we can send an email using the sendMail method:

const mailOptions = {
  from: 'youremail@gmail.com',
  to: 'recipient@example.com',
  subject: 'Test Email',
  text: 'Hi! This is an email sent using Node.js.',
};

transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    console.log('Error: ', error);
  } else {
    console.log('Email sent: ' + info.response);
  }
});

Conclusion

Sending emails with Node.js is simple and powerful thanks to libraries like nodemailer. Remember to follow best practices for credential management and test your code to ensure it works correctly.

Back to top