DEV Community

Cover image for Simple Emails Sending from Node.js Using Nodemailer and SMTP
Shivaji Zirpe
Shivaji Zirpe

Posted on

Simple Emails Sending from Node.js Using Nodemailer and SMTP

When building a web application, sending automated emails is a crucial feature for tasks like account verification, password resets, or notifications. my name is Shivaji Zirpe and In this blog post, we’ll explore how you can achieve this in your Node.js application using Nodemailer and SMTP.

What is Nodemailer?

Nodemailer is a popular Node.js library that makes sending emails easy. It supports various email services such as Gmail, Outlook, and custom SMTP servers.

Setting Up an SMTP Server

Before we dive into the implementation, ensure you have the following:

  1. SMTP Server Details: These are typically provided by your email service provider.
  2. SMTP Authentication Credentials: This includes the email address and password used to send emails.

Step-by-Step Implementation

1. Install Nodemailer

In your Node.js project, install Nodemailer using npm:

npm install nodemailer
Enter fullscreen mode Exit fullscreen mode

2. Create a Mail Transporter

In your project, set up a transporter using SMTP. The transporter handles the communication with the mail server:

const nodemailer = require('nodemailer');

// Create a transporter
const transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST, // SMTP host, e.g., smtp.mailprovider.com
  port: process.env.SMTP_PORT || 587, // Port (587 for TLS, 465 for SSL)
  secure: process.env.SMTP_PORT == 465, // Use SSL for port 465
  auth: {
    user: process.env.EMAIL_USERNAME, // SMTP username
    pass: process.env.EMAIL_PASSWORD, // SMTP password
  },
});
Enter fullscreen mode Exit fullscreen mode

In this code:

  • host: Specifies the SMTP host provided by your email service.
  • port: Use 587 for TLS or 465 for SSL.
  • secure: Set to true if you’re using port 465 (SSL).
  • auth: Your SMTP username and password for authentication.

3. Create Mail Options

Next, we create the mailOptions object, which holds the details of the email, such as sender, receiver, subject, and content:

const mailOptions = {
  from: process.env.EMAIL, // Sender's email address
  to: 'recipient@example.com', // Recipient's email address
  subject: "Your Subject", // Email subject
  html: `<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Your Title</title>
</head>
<body style="font-family: Helvetica, Arial;">
  <div>Here is your email content</div>
</body>
</html>`, // HTML content of the email
};
Enter fullscreen mode Exit fullscreen mode
  • from: Specifies the sender’s email.
  • to: Defines the recipient’s email.
  • subject: Contains the subject of the email.
  • html: The body of the email in HTML format, which can be customized with images, links, and styling.

4. Send the Email

Now that the transporter and mail options are ready, let's send the email:

transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    console.error("Error sending email:", error);
  } else {
    console.log("Email sent successfully:", info.response);
  }
});
Enter fullscreen mode Exit fullscreen mode

This code attempts to send the email. If there’s an error, it will be logged; otherwise, the email is sent successfully.

Environment Variables

It's important to keep sensitive information like SMTP credentials secure by storing them in environment variables. Create a .env file in your project root and include the following:

EMAIL=your_email
EMAIL_PASSWORD=your_password
SMTP_HOST=smtp.mailprovider.com
SMTP_PORT=587
EMAIL=your_email
Enter fullscreen mode Exit fullscreen mode

Ensure that your application loads the environment variables using the dotenv package:

npm install dotenv
Enter fullscreen mode Exit fullscreen mode

Then load it at the top of your file:

require('dotenv').config();
Enter fullscreen mode Exit fullscreen mode

Conclusion

Integrating email functionality into your Node.js application using Nodemailer and SMTP is a great way to manage automated emails for your app. Whether it's for transactional emails, marketing campaigns, or user notifications, this setup provides a flexible and straightforward approach.

Key Points:

  • Nodemailer simplifies the process of sending emails in Node.js.
  • Storing credentials in environment variables protects sensitive data.
  • HTML emails allow for customization with rich content and design.

With this setup, you're now ready to send emails from your Node.js application via any SMTP server!

Feel free to leave questions in the comments, and don’t forget to follow for more tutorials and checking out some of my work on GitHub or visiting my Portfolio. also connect over LinkedIn!


#Nodejs #Nodemailer #SMTP #EmailService #WebDevelopment

Top comments (0)