DEV Community

Cover image for How to send emails in Node.js (Detailed Steps)
The Open Coder
The Open Coder

Posted on

How to send emails in Node.js (Detailed Steps)

Node.js provides a simple and efficient way to send emails programmatically, without having to rely on a third-party service. In this article, we will explore the various ways to send emails in Node.js using the Nodemailer library, including adding attachments, CC and BCC, using templates, and handling environment variables.

1. Get started

Before we begin, we need to install the Nodemailer package. Open your terminal and run the following command:

npm install nodemailer
Enter fullscreen mode Exit fullscreen mode

This will install the Nodemailer package and add it to your package.json file.

2. Creating a Transporter

To send an email using Nodemailer, we first need to create a transporter. A transporter is an object that defines the server details and authentication credentials for sending emails. Here's an example of creating a transporter:

const nodemailer = require('nodemailer');

const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'your_email_address@gmail.com',
    pass: 'your_email_password'
  }
});
Enter fullscreen mode Exit fullscreen mode

Note that we are using the Gmail service and providing our email address and password for authentication. It is recommended to use environment variables instead of hardcoding these values.

3. Sending a Basic Email

Now that we have created a transporter, we can use it to send an email. Here's an example of sending a basic email:

const mailOptions = {
  from: 'your_email_address@gmail.com',
  to: 'recipient_email_address@gmail.com',
  subject: 'Sending an Email using Node.js',
  text: 'That was easy!'
};

transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    console.log(error);
  } else {
    console.log('Email sent: ' + info.response);
  }
});
Enter fullscreen mode Exit fullscreen mode

In the above code, we are defining the email details such as sender, recipient, subject, and text. The transporter.sendMail function is used to send the email. If the email is sent successfully, it will log a success message to the console.

4. Sending an HTML Email

In addition to plain text emails, we can also send HTML emails using Nodemailer. Here's an example of sending an HTML email:

const mailOptions = {
  from: 'your_email_address@gmail.com',
  to: 'recipient_email_address@gmail.com',
  subject: 'Sending an HTML Email using Node.js',
  html: '<h1>Welcome</h1><p>That was easy!</p>'
};
Enter fullscreen mode Exit fullscreen mode

Note that we are using the html property instead of the text property to define the email body.

5. Sending Attachments

Nodemailer also allows us to send attachments along with the email. Here's an example of sending an email with an attachment:

const mailOptions = {
  from: 'your_email_address@gmail.com',
  to: 'recipient_email_address@gmail.com',
  subject: 'Sending an Email with Attachment using Node.js',
  text: 'Check out the attachment!',
  attachments: [{
    filename: 'file.txt',
    path: '/path/to/file.txt'
  }]
};

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

6. Adding CC and BCC

In addition to sending emails to one or more recipients, you can also add CC (Carbon Copy) and BCC (Blind Carbon Copy) recipients to the email. Here's an example of sending an email with CC and BCC recipients using Nodemailer:

const mailOptions = {
  from: 'your_email_address@gmail.com',
  to: 'recipient_email_address@gmail.com',
  cc: 'cc_email_address1@gmail.com, cc_email_address2@gmail.com',
  bcc: 'bcc_email_address1@gmail.com, bcc_email_address2@gmail.com',
  subject: 'Sending an Email with CC and BCC using Node.js',
  text: 'This is the email body'
};
Enter fullscreen mode Exit fullscreen mode

7. Using Templates

Sending plain text emails is useful, but sometimes we need to send more complex and dynamic emails. In such cases, we can use email templates. Nodemailer provides support for email templates using various templating engines like Pug, Handlebars, EJS, and more. Here's an example of sending an email with a template using Nodemailer and Handlebars:

const handlebars = require('handlebars');
const fs = require('fs');

// Read the template file
const templateSource = fs.readFileSync('path_to_template_file.hbs', 'utf8');

// Compile the template
const template = handlebars.compile(templateSource);

// Render the template with the data
const html = template({name: 'John Doe'});

// Send the email
const mailOptions = {
  from: 'your_email_address@gmail.com',
  to: 'recipient_email_address@gmail.com',
  subject: 'Sending an Email with Template using Node.js',
  html: html
};
Enter fullscreen mode Exit fullscreen mode

8. Using Environment Variables

When working with sensitive information like email credentials, it's always best to store them as environment variables rather than hard-coding them in the code. Here's an example of using environment variables to store email credentials:

const nodemailer = require('nodemailer');

// Create a transporter object using the SMTP transport
const transporter = nodemailer.createTransport({
  host: process.env.EMAIL_HOST,
  port: process.env.EMAIL_PORT,
  secure: true, // use TLS
  auth: {
    user: process.env.EMAIL_USERNAME,
    pass: process.env.EMAIL_PASSWORD
  }
});

// Send the email
const mailOptions = {
  from: 'your_email_address@gmail.com',
  to: 'recipient_email_address@gmail.com',
  subject: 'Sending an Email with Environment Variables using Node.js',
  text: 'This is the email body'
};

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

Conclusion

I hope this article has been helpful in explaining how to send emails using Node.js with Nodemailer. With the ability to send plain text emails, attachments, CC and BCC recipients, templates, and the use of environment variables, you now have the tools to build robust email functionality into your Node.js applications.

👾Like my post?👾

I am also working on an Awesome Open Source project named: RATH.
Check it out on GitHub!

Top comments (0)