Send an email with attachment using Node.js

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.

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

2. Install Nodemailer

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

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

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.

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.

Multiple receivers

Send email to multiple users at a time.

Send HTML template

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

Send Attachment

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

5. Sending an email

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

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

6. Output

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

server.js

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

Demo & Source Code

GitHub Repository
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

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