How to send emails in Node.js

Sending emails programmatically is a fundamental requirement for most server-side applications, from user verification to notifications and reports. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented email functionality in countless Node.js applications throughout my 11 years of Node.js development. The most reliable approach is using Nodemailer with SMTP configuration, which provides a simple API for sending emails through any email service. This method is widely adopted and supports all major email providers.

Use Nodemailer to send emails through an SMTP server.

const nodemailer = require('nodemailer')

const transporter = nodemailer.createTransport({
  host: 'smtp.gmail.com',
  port: 587,
  secure: false,
  auth: {
    user: '[email protected]',
    pass: 'your-app-password'
  }
})

const mailOptions = {
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Test Email',
  text: 'This is a test email from Node.js'
}

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

Here a transporter is created with SMTP configuration including the host, port, and authentication credentials. The mailOptions object defines the sender, recipient, subject, and message content. The sendMail method sends the email asynchronously and provides a callback with error or success information.

Best Practice Note:

This is the same approach we use in CoreUI backend systems for sending notification emails. Always use environment variables to store email credentials, never hardcode them in your source code, and consider using app-specific passwords for Gmail or dedicated SMTP services like SendGrid for production environments.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team