How To Send Emails In Node.js + With Attachments

Tutorial of sending emails in node.js using nodemailer

Sending emails programmatically is a common requirement in web development, whether it’s for user notifications, password resets, or any other communication with users. In this step-by-step tutorial you will learn how to send emails in Node.js also with attachments using the NodeMailer library.

Step 1: Setting Up a Node.js Project

Before you start, make sure you have Node.js installed on your machine. Create a new directory called for this project and initialize a new Node.js project using the following commands:

mkdir node-send-emails
cd node-send-emails
npm init -y

Step 2: Generate App Password for Gmail SMTP

In this tutorial we will use Gmail SMTP with the nodemailer to send emails. Therefore we need a gmail address and the generated app password for the gmail.

To Generate a google app password, open the following link (make sure you are logged in and two-step verification is enabled), and generate an app password.

https://myaccount.google.com/apppasswords

1. Enter the App Name and Create:

Enter the App Name and click create button

2. Copy your Generated App Password and save it. My Generated App Password is – “tnxeizcecpwljdnt” Note: there is no space.

Gmail Generated App Password

Step 3: Install the Nodemailer Package

Create index.js at the root and set up a transporter to define the email service and authentication details. This example uses a Gmail account:

node-send-emails/
├── node_modules/
├── index.js
└── package.json
// Import nodemailer module
const nodemailer = require('nodemailer');

// Create a transporter using nodemailer
const transporter = nodemailer.createTransport({
    service: 'gmail', // Specify the email service provider
    auth: {
        user: '[email protected]', // Specify the sender's email address
        pass: 'your_google_generated_app_password', // Specify the app password generated for Gmail SMTP
    },
});

You can specify SMTP details manually, here’s an example:

const transporter = nodemailer.createTransport({
    host: 'smtp.forwardemail.net',
    port: 465,
    secure: true,
    auth: {
        // TODO: replace `user` and `pass` values from <https://forwardemail.net>
        user: '[email protected]',
        pass: 'REPLACE-WITH-YOUR-GENERATED-PASSWORD',
    },
});

Step 4: Construct the Email Message in Node.js for NodeMailer

Define the email message, including the sender, recipient, subject, and text or HTML content in an object:

const mailOptions = {
    from: '[email protected]', // Sender's email address
    to: '[email protected]', // Receiver's email address
    subject: 'Subject of the Email',
    text: 'This is the text content of the email.',
    html: '<p>This is the <strong>HTML content</strong> of the email.</p>',
};

Step 5: Send Emails in Node.js

Here is the complete code. Change the credentials according to yours:

const nodemailer = require('nodemailer');

// Create a transporter
const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: '[email protected]',
        pass: 'your_google_generated_app_password', // generate app password
    },
});

// Constructing the Email Message
const mailOptions = {
    from: '[email protected]', // Sender's email address
    to: '[email protected]', // Receiver's email address
    subject: 'Subject of the Email',
    text: 'This is the text content of the email.',
    html: '<p>This is the <strong>HTML content</strong> of the email.</p>',
};

// Sending the Email
transporter
    .sendMail(mailOptions)
    .then((info) => {
        console.log('Email sent:', info.response);
    })
    .catch((error) => {
        console.error(error);
    });

Execute the script and if everything is set up correctly, you should see a message indicating that the email has been sent.

node index.js

More on Sending Email in Node.js

1. Sending Email to Multiple Recipients

Sending emails to multiple recipients using Nodemailer in Node.js is straightforward. You can simply modify the to property in the mailOptions object to include an array of email addresses. Here’s an example:

const mailOptions = {
    from: '[email protected]', // Sender's email address
    to: ['[email protected]', '[email protected]'], // Array of receiver's email addresses
    subject: 'Hello from Node.js',
    text: 'This is a test email sent from Node.js with Nodemailer!',
};

If you have a large number of recipients, you might want to consider using the bcc (blind carbon copy) field instead of to.

The bcc field allows you to send the same email to multiple recipients without revealing each recipient’s email address to the others. Here’s an example using bcc:

const mailOptions = {
    from: '[email protected]', // Sender's email address
    bcc: ['[email protected]', '[email protected]'], // Array of recipient's email addresses
    subject: 'Hello from Node.js',
    text: 'This is a test email sent from Node.js with Nodemailer!',
};

2. Add Attachments with Emails:

To include attachments, add an attachments property to the mailOptions object:

const mailOptions = {
    // Other options...

    attachments: [
        {
            filename: 'file.txt',
            content: 'Attachment content as a string or Buffer',
        },
        // or
        {
            path: 'path/to/file.pdf',
        },
    ],
};

You can attach files by providing either the content directly or specifying the path to the file.

const nodemailer = require('nodemailer');

// Create a transporter
const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: '[email protected]',
        pass: 'your_google_generated_app_password', // generate app password
    },
});

// Constructing the Email Message
const mailOptions = {
    from: '[email protected]', // Sender's email address
    to: '[email protected]', // Receiver's email address
    subject: 'Subject of the Email',
    text: 'This is the text content of the email.',
    html: '<p>This is the <strong>HTML content</strong> of the email.</p>',

    attachments: [
        {
            filename: 'file.txt',
            content: 'Attachment content as a string or Buffer',
        },
    ],
};

// Sending the Email
transporter
    .sendMail(mailOptions)
    .then((info) => {
        console.log('Email sent:', info.response);
    })
    .catch((error) => {
        console.error(error);
    });

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy