Clue Mediator

Send an email with attachment using Node.js

📅August 12, 2021

In this article, we will send an email with attachment using Node.js. We will use the Nodemailer module and Gmail SMTP to send an email and also email with an attachment. It is very easy to send an email via Node.js.

Checkout more articles on Node.js

Steps to send an email using Node.js

  1. Setup node project using express
  2. Install Nodemailer
  3. Configure Gmail account
  4. Prepare options to send an email
  5. Sending an email
  6. Output

1. Setup node project using express

Here, we will use the express framework in Node.js to create a REST API. Kindly follow the link below if you don’t know how to create REST API in Node.js using express framework.

Create REST API in Node.js

server.js

var express = require('express'),
    app = express(),
    port = process.env.PORT || 4000;

// request handlers
app.get('/', (req, res) => {
    res.send('Welcome to the first Node.js Tutorial! - Clue Mediator');
});

app.listen(port, () => {
    console.log('Server started on: ' + port);
});

2. Install Nodemailer

Now, we need to install the Nodemailer by using the following command.

npm install nodemailer

After installing the Nodemailer, include the nodemailer module in your application.

var nodemailer = require('nodemailer');

3. Configure Gmail account

In this step, we have to create a Nodemailer transporter object by providing the details of the email account. It is required to send an email using Nodemailer to verify the sender information.

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

Set the service as gmail and provide your email address and password in the `auth` object. Before sending an email using gmail, you have to allow non secure apps to access the gmail.

Click here to turn on this setting.

4. Prepare options to send an email

We can use the following options to send an email.

var mailOptions = {
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Email Subject',
  text: 'Write your text message here...'
};

Multiple receivers

Send email to multiple users at a time.

var mailOptions = {
  from: '[email protected]',
  to: '[email protected],[email protected]',
  subject: 'Email Subject',
  text: 'Write your text message here...'
};

Send HTML template

To send HTML formatted content, we need to use the `html` property instead of `text` property.

var mailOptions = {
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Email Subject',
  html: '<p>send html formatted content here</p>'
};

Send Attachment

We can include a list of attachments which needs to be sent along with the mail.

var mailOptions = {
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Email Subject',
  text: 'Write your text message here...',
  attachments: [{
    filename: myfile.txt,
    path: '/path/to/file.txt'
  }]
};

5. Sending an email

Let’s use the above mail options and send an email using async await method.

// send mail with defined transport and mailOptions object
let info = await transporter.sendMail(mailOptions);

console.log('Email sent: % s', info.messageId);

Instead of async await, we can use the callback function to send an email.

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

6. Output

Let’s combine the code and check output. Here we will send an email on the GET method for demonstration.

server.js

var express = require('express'),
  app = express(),
  port = process.env.PORT || 4000;

var nodemailer = require('nodemailer');

// request handlers
app.get('/', async (req, res) => {
  var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: '[email protected]',
      pass: 'your-gmail-password'
    }
  });

  var mailOptions = {
    from: '[email protected]',
    to: '[email protected]',
    subject: 'Email Subject',
    text: 'Write your text message here...',
    attachments: [{
      filename: myfile.txt,
      path: '/path/to/file.txt'
    }]
  };

  let response = await transporter.sendMail(mailOptions);

  res.send({ response });
});

app.listen(port, () => {
  console.log('Server started on: ' + port);
});

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository