Sling Academy
Home/Node.js/How to Send Email in Node.js (3 Approaches)

How to Send Email in Node.js (3 Approaches)

Last updated: December 28, 2023

Solution 1: Using Nodemailer

Nodemailer is a popular Node.js module for sending emails. It supports multiple transport methods, including SMTP and direct sending.

  1. Install the ‘nodemailer’ package using npm: npm install nodemailer.
  2. Import the nodemailer module.
  3. Create a transporter object using SMTP credentials.
  4. Define your mail options, including from, to, subject, and text or HTML.
  5. Use the sendMail method of the transporter to send the email.
const nodemailer = require('nodemailer');
let transporter = nodemailer.createTransport({
  host: 'smtp.example.com',
  port: 587,
  secure: false,
  auth: {
    user: '[email protected]',
    pass: 'password'
  }
});

let mailOptions = {
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Test Email Subject',
  text: 'Hello world?',
  html: '<b>Hello world?</b>'
};

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

Pros: Easy to use; supports multiple transport options; widely used and tested.

Cons: Relies on external services; you need SMTP credentials.

Solution 2: Using SendGrid

SendGrid is a cloud-based email delivery service that offers a reliable way to send emails without managing email servers.

  1. Sign up for a SendGrid account and create an API key.
  2. Install the ‘@sendgrid/mail’ package: npm install @sendgrid/mail.
  3. Configure SendGrid with your API key.
  4. Use the send method to send an email.
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey('YOUR_SENDGRID_API_KEY');

const msg = {
  to: '[email protected]',
  from: '[email protected]',
  subject: 'Sending with SendGrid is Fun',
  text: 'and easy to do anywhere, even with Node.js',
  html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};

sgMail.send(msg).then(() => {
  console.log('Email sent');
}).catch((error) => {
  console.error(error);
});

Pros: Scalable; no need to manage email servers; good deliverability; official Node.js library support.

Cons: Can be expensive for large volumes; requires external API key setup.

Solution 3: Using Amazon SES

Amazon Simple Email Service (SES) is an email platform that provides an easy, cost-effective way to send and receive email using your own email addresses and domains.

  1. Create an AWS account and set up Amazon SES.
  2. Verify your email address or domain with Amazon SES.
  3. Install the ‘aws-sdk’ package: npm install aws-sdk.
  4. Configure AWS with your credentials.
  5. Implement the send email function using AWS SES.
const AWS = require('aws-sdk');

AWS.config.update({region: 'us-west-2'});
const ses = new AWS.SES({apiVersion: '2010-12-01'});

let params = {
  Destination: {
    ToAddresses: [
      '[email protected]'
    ]
  },
  Message: {
    Body: {
      Text: { Data: 'Hello from Amazon SES!' }
    },
    Subject: { Data: 'Test Email' }
  },
  Source: '[email protected]'
};

ses.sendEmail(params, function(err, data) {
  if (err) console.log(err, err.stack);
  else     console.log(data);
});

Pros: Integrates well with AWS services; cost-effective; high deliverability.

Cons: Higher complexity due to AWS setup; limited free tier.

Conclusion

Sending emails in Node.js can be accomplished with a variety of methods, each with their own set of pros and cons. Developers should choose based on their project requirements, preferred pricing, and the scalability they need. Nodemailer is a good all-rounder if you already have SMTP setup, SendGrid is excellent for those needing high deliverability, and Amazon SES suits those deeply embedded in the AWS ecosystem. Keep security in mind and never expose sensitive credentials in your codebase.

Next Article: 3 Ways to Convert Callbacks to Promises in Node.js

Previous Article: Should you use Docker or PM2 to run Node.js apps in production

Series: Node.js Intermediate Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates