How To Send Emails In Node.js With Attachments?

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 the Node.js ecosystem, Nodemailer is a widely used library that simplifies the process of sending emails.

In this guide, we will walk through the steps to send emails in Node.js with Attachments using Nodemailer.

Table of Contents #
  1. Setting Up a Node.js Project
  2. Install Nodemailer
  3. Creating an Email Transporter
  4. Generate App Password
  5. Update Email and Password
  6. Constructing the Email Message
  7. Sending the Email with Handling Errors
  8. Full Code (“sendEmail.js”)
  9. Advanced Configuration
  10. Best Practices and Considerations
  11. Conclusion

1. Setting Up a Node.js Project

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

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

2. Install Nodemailer

Nodemailer can be installed using npm, the Node.js package manager. Run the following command in your project directory:

npm install nodemailer

3. Creating an Email Transporter

Set up a transporter to define the email service and authentication details. This example uses a Gmail account:

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
    },
});

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',
    },
});

4. Generate App Password

This example uses Gmail, if you’re using it too, you’ll need to generate an app password.

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 Create
  2. Copy the Generated App Password:

    My Generated App Password is – “tnxeizcecpwljdnt” Note: there is no space.

    Copy the Generated App Password

5. Update Email and Password

After getting the generated app password, replace the transporter credential with yours (“[email protected]” & “your_email_password”).

6. Constructing the Email Message

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

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>',
};

6.1. Sending Email to Multiple Recipients via Nodemailer

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!',
};

In this example, the to property is an array that contains multiple recipient email addresses. Nodemailer will send the email to all the addresses specified in the array.

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!',
};

6.2. Adding Attachments

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',
        },
        {
            path: 'path/to/file.pdf',
        },
    ],
};

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

7. Sending the Email with Handling Errors

Use the transporter to send the email:

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

This code sends the email and logs the response.

8. Full Code (“sendEmail.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>',

    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);
    });

Execute the script using the following command:

node sendEmail.js

If everything is set up correctly, you should see a message indicating that the email has been sent.

9. Advanced Configuration

Nodemailer supports various configurations, such as using different transport methods (SMTP, sendmail, etc.) and additional settings. Refer to the Nodemailer documentation for advanced configurations.

10. Best Practices and Considerations

  1. Use Environment Variables: Avoid hardcoding sensitive information like email credentials directly in your code. Instead, use environment variables or a configuration file.
  2. Use App Password: Using your email password directly is not recommended; consider using an App Password if you are using Gmail.
  3. Handle Errors Gracefully: Implement error handling to gracefully manage any issues that may arise during the email sending process.
  4. Third-Party Services: For improved deliverability and additional features you can use third-party email services like SendGrid, Mailgun, or Amazon SES.

Conclusion

Sending emails with attachments in Node.js is made straightforward with the Nodemailer library.

By following the steps outlined in this guide, you can quickly integrate email functionality into your Node.js applications and enhance communication with users.

Experiment with the library’s features to explore additional capabilities and customization options based on your application’s requirements.