Sending Emails with Nodemailer in Node.js

Sending Emails with Nodemailer in Node.js

Are you looking to add email functionality to your Node.js application? Whether you're building a contact form, sending notifications, or automating email workflows, this tutorial is your ultimate guide to getting started. Using Nodemailer, a powerful and easy-to-use Node.js library, we'll walk you through every step of sending emails programmatically. From setting up your project to sending emails with attachments, this tutorial is designed to be beginner-friendly while covering advanced features for seasoned developers.

By the end of this tutorial, you'll have a fully functional email-sending system integrated into your Node.js application. You'll also learn best practices like securing your credentials with environment variables and testing your setup with a fake SMTP server. Ready to take your Node.js skills to the next level? Dive into the tutorial and start sending emails like a pro today!

Prerequisites

Before starting, ensure you have the following:

  • Node.js installed on your machine (read here how to do it).
  • A Gmail account (or any other email service provider) for sending emails.
  • Basic knowledge of JavaScript and Node.js.

Step 1: Set Up Your Node.js Project

1. Create a new directory for your project:

mkdir nodemailer-tutorial
cd nodemailer-tutorial

2. Initialize a new Node.js project:

npm init -y

3. Install the Nodemailer library:

npm install nodemailer --save

    Step 2: Configure Nodemailer

    Nodemailer requires a transport object to send emails. For this tutorial, we'll use Gmail as the email service provider.

    1. Create a new file called index.js:

    touch index.js

    2. Open the file and add the following code to set up Nodemailer:

    1// Step 1: Import Nodemailer
    2const nodemailer = require('nodemailer');
    3
    4// Step 2: Create a transporter object
    5const transporter = nodemailer.createTransport({
    6    service: 'gmail', // Use Gmail as the service
    7    auth: {
    8        user: '[email protected]', // Your Gmail address
    9        pass: 'your-app-password', // Your Gmail app password (not your regular password)
    10    },
    11});
    12
    13// Step 3: Define email options
    14const mailOptions = {
    15    from: '[email protected]', // Sender address
    16    to: '[email protected]', // Recipient address
    17    subject: 'Hello from Nodemailer!', // Email subject
    18    text: 'This is a test email sent using Nodemailer.', // Plain text body
    19    html: '<h1>Hello!</h1><p>This is a test email sent using <b>Nodemailer</b>.</p>', // HTML body
    20};
    21
    22// Step 4: Send the email
    23transporter.sendMail(mailOptions, (error, info) => {
    24    if (error) {
    25        console.error('Error sending email:', error);
    26    } else {
    27        console.log('Email sent:', info.response);
    28    }
    29});

    Step 3: Generate an App Password for Gmail

    Since Gmail requires additional security for third-party apps, you'll need to generate an app password:

    • Go to your Google Account settings: https://myaccount.google.com.
    • Enable 2-Step Verification if it's not already enabled.
    • Generate an app password:
      • Go to Security > App Passwords.
      • Select Mail as the app and Other as the device.
      • Copy the generated password and use it in the auth.pass field in the code above.

    Step 4: Run the Code

    • Save the index.js file.
    • Run the script using Node.js:
      node index.js
    • If everything is set up correctly, you should see a success message like:
      Email sent: 250 2.0.0 OK  1234567890abcdef-1234567890abcdef
    • Check the recipient's inbox for the email.

    Step 5: Sending Emails with Attachments

    You can also send emails with attachments using Nodemailer. Update the mailOptions object as follows:

    1const mailOptions = {
    2    from: '[email protected]',
    3    to: '[email protected]',
    4    subject: 'Email with Attachment',
    5    text: 'This email contains an attachment.',
    6    html: '<h1>Check this out!</h1><p>This email contains an attachment.</p>',
    7    attachments: [
    8        {
    9            filename: 'example.txt', // Name of the attachment
    10            content: 'This is a text file attachment.', // Content of the attachment
    11        },
    12        {
    13            filename: 'image.png', // Name of the image attachment
    14            path: __dirname + '/image.png', // Path to the image file
    15        },
    16    ],
    17};

    Step 6: Using Environment Variables

    For security reasons, avoid hardcoding sensitive information like email credentials. Use environment variables instead:

    • Install the dotenv package:
      npm install dotenv
    • Create a .env file:
      touch .env
    • Add your credentials to the .env file:
      EMAIL_USER=[email protected]
      EMAIL_PASS=your-app-password
    • Update index.js to use environment variables:
      1require('dotenv').config();
      2
      3const transporter = nodemailer.createTransport({
      4    service: 'gmail',
      5    auth: {
      6        user: process.env.EMAIL_USER,
      7        pass: process.env.EMAIL_PASS,
      8    },
      9});

    Step 7: Testing with a Fake SMTP Server

    If you don't want to use a real email account, you can test your code using a fake SMTP server like Mailtrap:

    • Sign up for a free account at Mailtrap.
    • Update the transporter configuration:
    1const transporter = nodemailer.createTransport({
    2    host: 'sandbox.smtp.mailtrap.io',
    3    port: 2525,
    4    auth: {
    5        user: 'your-mailtrap-username',
    6        pass: 'your-mailtrap-password',
    7    },
    8});

    Conclusion

    You've successfully learned how to send emails using Node.js and Nodemailer! You can now:

    • Send plain text and HTML emails.
    • Add attachments to your emails.
    • Use environment variables for secure credential management.
    • Test your code with a fake SMTP server.

    Feel free to explore Nodemailer's official documentation for more advanced features like templates, custom SMTP servers, and more.

    Related articles