3 Ways to Send Emails in NestJS

Updated: January 1, 2024 By: Guest Contributor Post a comment

Introduction

Sending emails is a common task in web applications, and NestJS with its modular structure facilitates this through various methods. Here are three effective solutions to send emails in NestJS.

Solution 1: Using Nodemailer

Nodemailer is a popular node.js library used for sending emails easily. It provides several transport options and can be smoothly integrated into a NestJS application.

The steps:

  • First, install the Nodemailer package using npm or yarn.
  • Next, create a mail module and service.
  • Configure the transporter with your SMTP settings.
  • Use the service within your application to send emails.

Complete Code Example:


import { Injectable } from '@nestjs/common';
import * as nodemailer from 'nodemailer';

@Injectable()
export class EmailService {
  private transporter;
  constructor() {
    this.transporter = nodemailer.createTransport({
      host: 'smtp.example.com',
      port: 587,
      secure: false, // true for 465, false for other ports
      auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASS,
      },
    });
  }

  async sendMail(to: string, subject: string, text: string, html: string) {
    const mailOptions = {
      from: '"Example" <[email protected]>',
      to, subject, text, html,
    };

    const info = await this.transporter.sendMail(mailOptions);
    return info;
  }
}

Pros:

  • Widely used and well-documented.
  • Flexible with various SMTP services and supports attachments.

Cons:

  • Additional configuration required for different SMTP services.
  • Need to manage SMTP service credentials securely.

Solution 2: Using @nestjs-modules/mailer

The @nestjs-modules/mailer package is designed for NestJS as a wrapper around Nodemailer, which provides easier configuration and usage specific to the framework.

The steps:

  • Install the package along with Nodemailer.
  • Create and configure the MailerModule within your application.
  • Create a mail service to use the MailerService for sending emails.

Complete Code Example:


import { Module } from '@nestjs/common';
import { MailerModule } from '@nestjs-modules/mailer';
import { EmailService } from './email.service';

@Module({
  imports: [
    MailerModule.forRoot({
      transport: {
        host: 'smtp.example.com',
        port: 587,
        ignoreTLS: false,
        secure: false, // true for 465, false for other ports
        auth: {
          user: process.env.EMAIL_USER,
          pass: process.env.EMAIL_PASS,
        },
      },
      defaults: {
        from: '"No Reply" <[email protected]>',
      },
    }),
  ],
  providers: [EmailService],
})
export class EmailModule {}

Pros:

  • Seamless integration with NestJS.
  • Allows template engines for email contents.

Cons:

  • Can be less flexible than using Nodemailer directly.
  • Package updates depend on the community.

Solution 3: Using External Email API Services

External API services like SendGrid or Mailgun offer reliable email delivery solutions with additional tracking and analytics. They often offer easy integration with NestJS through their API.

TL;DR:

  • Create an account and set up your email domain with the service.
  • Install any necessary client libraries or use HTTP requests with the Fetch API.
  • Configure the API keys and integrate the email sending functionality in a service.

Complete Code Example:


import { Injectable } from '@nestjs/common';
import * as sgMail from '@sendgrid/mail';

@Injectable()
export class EmailService {
  constructor() {
    sgMail.setApiKey(process.env.SENDGRID_API_KEY);
  }

  async sendMail(to: string, subject: string, text: string) {
    const msg = {
      to,
      from: '[email protected]',
      subject,
      text,
    };

    const response = await sgMail.send(msg);
    return response;
  }
}

Pros:

  • Managed service with enhanced email deliverability.
  • Additional features like analytics and enhanced security.

Cons:

  • May incur additional costs depending on usage.
  • Reliance on an external service’s uptime and availability.

Conclusion

In conclusion, each of the mentioned solutions for sending emails in NestJS has its own set of advantages and considerations. Direct integration with Nodemailer provides extensive control, while using the @nestjs-modules/mailer offers tight integration with NestJS. On the other hand, external email services like SendGrid or Mailgun provide ready-to-use APIs with extra features for email management and analytics. The choice depends on the specific requirements of the project including factors like simplicity, extensibility, reliability, and cost.