How to send email with attachment in Node.js

How to send email with attachment in Node.js

In this guide we are going to discuss about send email via nodejs. We will use nodemailer module amd gmail smtp to send the email. We will also learn how to send email with attachment. So let’s get started with the node js send email with attachment tutorial

Email is one of the most used tools for communication in web applications because it helps you reach your users directly, build your brand, or send general notifications.

So, you are thinking about sending emails from your next great Node.js application. Today we are going to discuss about send email via nodejs. We will use nodemailer module amd gmail smtp to send the email. We will also learn how to send email with attachment. So let’s get started with the node js send email with attachment tutorial

Installing Nodemailer

npm install nodemailer

Next, include the nodemailer module in your application

var nodemailer = require('nodemailer');

Configure Nodemailer with Gmail

The nodemailer needs a transport service using which it can send emails. Use the username and password from your selected email provider to send an email. This tutorial will show you how to use your Gmail account to send an email:


var mail = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: '[email protected]',
    pass: 'your-gmail-password'
  }
});

Before sending email using gmail you have to allow non secure apps to access gmail you can do this by going to your gmail settings here.

Once less secure apps is enabled now nodemailer can use your gmail for sending the emails.

Sending Email

Now you are ready to send emails from your server.


var mailOptions = {
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Sending Email via Node.js',
  text: 'That was easy!'
};

transporter.sendMail(mailOptions, function(error, info){
  if (error) {
    console.log(error);
  } else {
    console.log('Email sent: ' + info.response);
  }
});

Multiple Receivers

Send email to multiple user at same time

var mailOptions = {
  from: '[email protected]',
  to: '[email protected], [email protected]',
  subject: 'Sending Email using Node.js',
  text: 'That was easy!'
}

Send HTML

To send HTML formatted text in your email, use the “html” property instead of the “text” property:


var mailOptions = {
   from: '[email protected]',
   to: '[email protected], [email protected]',
   subject: 'Sending Email using Node.js',
   html: '<h1>Welcome</h1><p>That was easy!</p>' 
 }

Send Attachment

attachments option in the message object that contains an array of attachment objects.


var mailOptions = {
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Sending Email using Node.js',
  text: 'That was easy!',
  attachments: [{   // utf-8 string as an attachment
            filename: 'text1.txt',
            content: 'hello world!'
        },
        {   // binary buffer as an attachment
            filename: 'text2.txt',
            content: new Buffer('hello world!','utf-8')
        },
        {   // file on disk as an attachment
            filename: 'text3.txt',
            path: '/path/to/file.txt' // stream this file
        },
        {   // filename and content type is derived from path
            path: '/path/to/file.txt'
        },
        {   // stream as an attachment
            filename: 'text4.txt',
            content: fs.createReadStream('file.txt')
        },
        {   // define custom content type for the attachment
            filename: 'text.bin',
            content: 'hello world!',
            contentType: 'text/plain'
        },
        {   // use URL as an attachment
            filename: 'license.txt',
            path: 'https://raw.github.com/nodemailer/nodemailer/master/LICENSE'
        },
        {   // encoded string as an attachment
            filename: 'text1.txt',
            content: 'aGVsbG8gd29ybGQh',
            encoding: 'base64'
        },
        {   // data uri as an attachment
            path: 'data:text/plain;base64,aGVsbG8gd29ybGQ='
        }
    ]
}

After above changes our app.js file will looks like this

var nodemailer = require('nodemailer');

var mail = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: '[email protected]',
    pass: 'your-gmail-password'
  }
});

var mailOptions = {
   from: '[email protected]',
   to: '[email protected], [email protected]',
   subject: 'Sending Email using Node.js',
   html: '<h1>Welcome</h1><p>That was easy!</p>' ,
   attachments: [{
       filename: 'text1.txt',
       content: 'hello world!'
   }
}

mail.sendMail(mailOptions, function(error, info){
      if (error) {
        console.log(error);
      } else {
        console.log('Email sent: ' + info.response);
      }
});

Conclusion

You can now easily send personalized emails in your Node.js code using the nodemailer module. And don't forget, the nodemailer documentation is your best friend for learning about the more advanced options.

Learn More

Thanks for reading !

nodejs javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire NodeJs Developer

Looking to build dynamic, extensively featured, and full-fledged web applications? **[Hire NodeJs Developer](https://hourlydeveloper.io/hire-dedicated-node-js-developer/ "Hire NodeJs Developer")** to create a real-time, faster, and scalable...

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

Hire Nodejs Developer

Looking to **hire NodeJS Developer**[https://www.dataeximit.com/node-js-development/](https://www.dataeximit.com/node-js-development/ "https://www.dataeximit.com/node-js-development/") to build a perfect back-end to your website or...

What is ECMAScript and How is it Different From JavaScript?

Many times developers use JavaScript and ECMAScript synonymously for each other. Though they are very closely linked to each other, it does not mean they are the same thing.here is a complete story on the history of JavaScript and how it came into existence. To cut the long story short, ECMA in ECMAScript refers to Europen Computer Manufacturers Association to which JavaScript 1.1 was submitted for standardization back in the year 1997.

Data Types In JavaScript

JavaScript data types are kept easy. While JavaScript data types are mostly similar to other programming languages; some of its data types can be unique. Here, we’ll outline the data types of JavaScript.