Sending emails is an important functionality for a backend application. Sendgrid is a great option when it comes to sending emails from a NestJS application. In this post, we will look at step-by-step approach to send email using Sendgrid and NestJS integration.

To use Sendgrid in NestJS, we can use the @sendgrid/mail npm package. By using this package, we can use the Sendgrid API to send an email. This makes the configuration part extremely simple.

1 – Installing Sendgrid Mail Package

Sendgrid is a cloud-based SMTP provider. It allows us to send emails without maintaining our own servers.

To get started with Sendgrid email in NestJS, we need to install a couple of packages.

$ npm install @nestjs/config @sendgrid/mail

The @sendgrid/mail package provides functions to connect with Sendgrid. On the other hand, the @nestjs/config package helps us configure Sendgrid credentials.

If interested, you can check out this detailed post on managing NestJS Config.

By the way, if you are interested in backend frameworks and concepts, you’d love the Progressive Coder family where I explain these concepts in a fun and interesting manner.

Subscribe now and join along.

2 – NestJS Sendgrid Configuration Setup

The first step is to configure Sendgrid to work with our NestJS application.

To do so, we will import ConfigModule within our App module. See below:

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { MailController } from './mail.controller';
import { SendgridService } from './sendgrid.service';

@Module({
  imports: [ConfigModule.forRoot()],
  controllers: [AppController, MailController],
  providers: [AppService, SendgridService],
})
export class AppModule {}

The ConfigModule.forRoot() basically sets up a bare minimum configuration for our NestJS application. At the time of application startup, NestJS will look for a file named .env inside the root project directory for environment variables.

See below our .env file.

SEND_GRID_KEY=<YOUR_API_KEY>

We currently have only one environment variable i.e. the SEND_GRID_KEY. This is the API key we have to generate by logging into our Sendgrid account. You can check out the official Sendgrid docs on how to create an API key.

With this, our configuration is done. At this point, please ignore the SendgridService and MailController. We will be creating them in the next section.

3 – Creating the Sendgrid Mail Service

We need to now create a service to send emails. We will call the service as SendgridService.

import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import * as SendGrid from '@sendgrid/mail';

@Injectable()
export class SendgridService {
    constructor(private readonly configService: ConfigService) {
        SendGrid.setApiKey(this.configService.get<string>('SEND_GRID_KEY'));
    }

    async send(mail: SendGrid.MailDataRequired) {
        const transport = await SendGrid.send(mail);

        console.log(`Email successfully dispatched to ${mail.to}`)
        return transport;
    }
}

Basically, SendgridService is a typical NestJS Provider class. The class is annotated with @Injectable() decorator.

Within the constructor, we inject an instance of the ConfigService. Basically, the ConfigService provides access to the environment variables. We can use the get() method to fetch the SEND_GRID_KEY.

We also call the static method setApiKey() available as part of the Sendgrid class to set our send grid key. In other words, we are connecting our NestJS application to the Sendgrid account.

Lastly, we declare a method send() to actually send the email. This method takes a SendGrid.MailDataRequired object and passes it to SendGrid.send() method.

4 – Trigger the NestJS Sendgrid Email

The last step is to actually trigger the email. This can be done in several ways. For example, we might have a scheduler that sends emails at fixed intervals. Also, we can trigger the email when some event occurs in our application.

For our demo application, we will simply create a NestJS Controller endpoint to trigger the SendgridService.

import { Controller, Post, Query } from "@nestjs/common";
import { SendgridService } from "./sendgrid.service";

@Controller('mail')
export class MailController {
    constructor(
        private readonly sendgridService: SendgridService
    ){}

    @Post('send')
    async sendEmail(@Query('email') email) {
        const mail = {
            to: email,
            subject: 'Greeting Message from NestJS Sendgrid',
            from: '<send_grid_email_address>',
            text: 'Hello World from NestJS Sendgrid',
            html: '<h1>Hello World from NestJS Sendgrid</h1>'
        };

        return await this.sendgridService.send(mail);
    }
}

Basically, we inject an instance of the SendgridService. As part of the request handler, we accept the to email address as input.

Then, we create the mail object along with the email text/content and finally call the send() function of the SendgridService.

Note here that the from address should be a verified sender created and verified by you in your Sendgrid account. Using any other arbitrary email address will throw an error.

You can now start the application using npm run start and test the email sending by issuing a POST request to http://localhost:3000/mail/send?email=<receiver_email_address>.

Conclusion

With this, our NestJS Send Email example is complete. By using NestJS Configuration and Sendgrid API, sending emails from our NestJS application becomes extremely simple. Basically, the configuration setup is quite easy once we have a valid API key at our disposal.

However, in this example, our email itself is pretty static. We can also use templating in our emails to make them more dynamic. Also, instead of Sendgrid API, we can use Sendgrid Twilio SMTP to send the email. If interested to know more about it, check out this post about sending email using NestJS and Nodemailer with Handlebars.

If you have any comments or queries about this post, please mention them in the comments section below.

Anyways, before we end this post, a quick reminder about the Progressive Code Newsletter where I explain about backend frameworks and concepts in a fun & interesting manner so that you never forget what you’ve learned.

I’m 100% sure you’d love it.

Subscribe now and see you over there.

Categories: BlogNestJS

Saurabh Dashora

Saurabh is a Software Architect with over 12 years of experience. He has worked on large-scale distributed systems across various domains and organizations. He is also a passionate Technical Writer and loves sharing knowledge in the community.

0 Comments

Leave a Reply

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