Send Email with Attachment in Node.js

Introduction

Sending emails is a common feature in modern web applications. Sometimes, an email needs to include a file such as an invoice, PDF document, report, image, or receipt.

Node.js makes it possible to send emails with attachments using the Nodemailer package. Nodemailer allows developers to specify the email recipient, subject, message, and one or more files to attach.

What Is an Email Attachment?

An email attachment is a file sent along with an email message. The recipient can usually download or open the attached file using their email application.

Common examples include:

  • PDF invoices and receipts.
  • Word documents and spreadsheets.
  • Images and photographs.
  • Reports and certificates.
  • Other supported file types.

In Node.js, you can use Nodemailer to attach files by specifying an attachments property in the email message.

What Is Nodemailer?

Nodemailer is a Node.js module that allows applications to send email messages through SMTP and other supported transports.

It supports several useful features, including:

  • Sending plain-text and HTML emails.
  • Attaching files to email messages.
  • Sending multiple attachments in one email.
  • Specifying attachment filenames.
  • Handling asynchronous email-sending operations.
  • Returning information about submitted messages.

Prerequisites

Before starting, make sure you have:

  • Node.js installed on your computer.
  • npm installed.
  • Basic knowledge of JavaScript.
  • Nodemailer installed in your project.
  • Access to a working SMTP service or email provider.
  • Valid SMTP credentials and permission to use the sender address.

Step 1: Create a Node.js Project

Create a new folder for the project:


mkdir email-attachment-demo
cd email-attachment-demo

Initialize the project:


npm init -y

This command creates a package.json file for your Node.js application.

Step 2: Install Nodemailer

Install Nodemailer using npm:


npm install nodemailer

For local development, you can also install dotenv to load SMTP configuration from a .env file:


npm install dotenv

Step 3: Configure SMTP Credentials

Create a .env file in your project folder:


SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_SECURE=false
SMTP_USER=your-smtp-username
SMTP_PASS=your-smtp-password
EMAIL_FROM=My Website <verified@example.com>

Replace the sample values with the settings supplied by your email provider.

For many providers, port 465 uses implicit TLS, while port 587 commonly uses STARTTLS. Follow your provider’s documentation for the correct host, port, security settings, and authentication method.

Add .env to .gitignore so credentials are not accidentally committed to version control:


.env
node_modules/

Never publish your SMTP credentials or upload them to a public repository.

Step 4: Create an Email-Sending Program

Create a file named sendAttachment.js.

First, load the required packages and configure the transporter:


require("dotenv").config();

const nodemailer = require("nodemailer");
const path = require("path");

const transporter = nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: Number(process.env.SMTP_PORT),
    secure: process.env.SMTP_SECURE === "true",
    auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASS
    }
});

The transporter connects your Node.js application to the configured email service.

The path module will help construct file paths in a platform-independent way.

Step 5: Send an Email with a PDF Attachment

Suppose your project contains the following file:


email-attachment-demo/
├── node_modules/
├── files/
│   └── invoice.pdf
├── .env
├── package.json
└── sendAttachment.js

Create the files folder and place a test PDF named invoice.pdf inside it.

Now add the following code below the transporter configuration:


async function sendEmailWithAttachment() {
    try {
        const filePath = path.join(
            __dirname,
            "files",
            "invoice.pdf"
        );

        const info = await transporter.sendMail({
            from: process.env.EMAIL_FROM,
            to: "recipient@example.com",
            subject: "Your Invoice",
            text: "Hello, please find your invoice attached.",
            attachments: [
                {
                    filename: "invoice.pdf",
                    path: filePath
                }
            ]
        });

        console.log("Email submitted:", info.messageId);
    } catch (error) {
        console.error("Failed to send email:", error.message);
    }
}

sendEmailWithAttachment();

Replace recipient@example.com with an email address you can access.

Explanation of the Code

  • path.join() constructs the path to the PDF file.
  • __dirname represents the directory containing the current JavaScript file.
  • from specifies the sender address.
  • to specifies the recipient address.
  • subject defines the email subject.
  • text contains the email message.
  • attachments contains the files to attach.
  • filename specifies the name shown to the recipient.
  • path specifies the location of the attachment on the server.
  • sendMail() submits the email using the configured transporter.

The file must exist, and the Node.js process must have permission to read it.

Step 6: Run the Program

Execute the following command in your terminal:


node sendAttachment.js

If the SMTP configuration is correct and the email service accepts the message, the program will display a message ID.

A successful submission does not guarantee that the email has reached the recipient’s inbox. The recipient’s mail server may still reject the message or place it in the spam folder.

Step 7: Send an Email with an Image Attachment

You can also attach image files, such as PNG or JPEG images.

For example:


const info = await transporter.sendMail({
    from: process.env.EMAIL_FROM,
    to: "recipient@example.com",
    subject: "Image Attachment Example",
    text: "Please find the image attached.",
    attachments: [
        {
            filename: "product-image.png",
            path: path.join(
                __dirname,
                "files",
                "product-image.png"
            )
        }
    ]
});

Make sure product-image.png exists in the files folder.

This approach is useful for applications that send product images, event photographs, or other image files.

Step 8: Send an Email with Multiple Attachments

Nodemailer allows you to attach multiple files to a single email by adding multiple objects to the attachments array.

For example, you can send an invoice and a report together:


const info = await transporter.sendMail({
    from: process.env.EMAIL_FROM,
    to: "recipient@example.com",
    subject: "Invoice and Report",
    text: "Please find the invoice and report attached.",
    attachments: [
        {
            filename: "invoice.pdf",
            path: path.join(__dirname, "files", "invoice.pdf")
        },
        {
            filename: "report.pdf",
            path: path.join(__dirname, "files", "report.pdf")
        }
    ]
});

In this example, both files are attached to the same email.

You can add additional attachment objects when required, subject to your email provider’s attachment count and message-size limits.

Step 9: Send an Email with a Custom Attachment Filename

Sometimes, you may want the recipient to see a different filename from the original file stored on your server.

You can use the filename property to specify the name displayed in the email:


const info = await transporter.sendMail({
    from: process.env.EMAIL_FROM,
    to: "recipient@example.com",
    subject: "Monthly Report",
    text: "Please find the monthly report attached.",
    attachments: [
        {
            filename: "Monthly-Report-October.pdf",
            path: path.join(__dirname, "files", "report.pdf")
        }
    ]
});

Here, the file stored on the server is named report.pdf, but the recipient sees Monthly-Report-October.pdf as the attachment name.

This is useful when sending invoices, monthly reports, certificates, and other automatically generated documents.

Step 10: Send an Email with HTML Content and an Attachment

Nodemailer also allows you to combine an HTML email body with file attachments.


const info = await transporter.sendMail({
    from: process.env.EMAIL_FROM,
    to: "recipient@example.com",
    subject: "Your Order Confirmation",
    text: "Thank you for your order. Your invoice is attached.",
    html: `
        <h2>Thank You for Your Order!</h2>
        <p>Your order has been confirmed.</p>
        <p>Please find your invoice attached to this email.</p>
    `,
    attachments: [
        {
            filename: "invoice.pdf",
            path: path.join(__dirname, "files", "invoice.pdf")
        }
    ]
});

The recipient receives a formatted email with the invoice attached. Providing both text and html helps support different email clients.

Step 11: Attach a File Using a Buffer

A file does not always need to be read from a local path. Nodemailer also supports attachments using a Buffer.

This is useful when a PDF or report has already been generated in memory.


const fs = require("fs");

const fileBuffer = fs.readFileSync(
    path.join(__dirname, "files", "invoice.pdf")
);

const info = await transporter.sendMail({
    from: process.env.EMAIL_FROM,
    to: "recipient@example.com",
    subject: "Invoice Attachment",
    text: "Please find your invoice attached.",
    attachments: [
        {
            filename: "invoice.pdf",
            content: fileBuffer,
            contentType: "application/pdf"
        }
    ]
});

Here, fs.readFileSync() reads the file into memory, and content provides the resulting buffer to Nodemailer.

For larger files or applications handling many simultaneous requests, consider streaming files or using another non-blocking file-access approach instead of reading large files synchronously.

Common Mistakes When Sending Email Attachments

Mistake Solution
Incorrect file path Use path.join(__dirname, …) and verify the file exists.
File does not exist Check the filename, extension, and folder location.
Missing read permissions Ensure the Node.js process can read the file.
Incorrect SMTP settings Verify the host, port, TLS settings, and credentials.
Oversized attachment Check the provider’s message-size limits and reduce or compress the file if appropriate.
Unhandled errors Use try…catch around asynchronous email operations.
Hardcoded credentials Store secrets in environment variables or a secret manager.
User-controlled file paths Restrict files to authorized locations and validate access.

Security Best Practices

Follow these practices when sending attachments in a production application:

  1. Validate file access: Ensure the user is authorized to send or access the attached file.
  2. Avoid arbitrary file paths: Never let untrusted users choose unrestricted server file paths.
  3. Protect sensitive documents: Use appropriate authorization and access controls for invoices, reports, and personal records.
  4. Limit attachment sizes: Apply reasonable limits and follow the email provider’s message-size restrictions.
  5. Protect SMTP credentials: Never expose passwords, API keys, or tokens in source code.
  6. Use secure email connections: Follow the email provider’s TLS and authentication requirements.
  7. Handle errors carefully: Log useful diagnostic details without exposing secrets or confidential document contents.
  8. Prevent email abuse: Apply rate limits and authorization checks to endpoints that send emails.
  9. Be careful with untrusted files: Validate uploaded files and scan them when appropriate before attaching or distributing them.

Real-Life Example of Sending an Invoice

Imagine an online shopping application that sends an invoice after a customer places an order.

The application can follow this process:

  1. The customer places an order.
  2. The server saves the order details.
  3. The application generates a PDF invoice.
  4. Nodemailer attaches the invoice to an email.
  5. The email service processes the message for delivery.

For reliable processing, important email jobs can be placed in a background queue. The application should also record failures and retry temporary errors carefully.

Conclusion

Sending email with attachments in Node.js is straightforward with Nodemailer. You can attach PDF documents, images, multiple files, and generated buffers by configuring the attachments property in your email message.

This feature is useful for invoices, reports, certificates, order confirmations, and other automated notifications. For production applications, protect credentials, validate file access, limit attachment sizes, and handle email errors properly.

By following these steps, you can integrate email attachments into your Node.js applications safely and reliably.

Related Node.js Tutorials