DEV Community

Cover image for Simple Email Integration in NestJS with SendGrid
Ashish Patel
Ashish Patel

Posted on

Simple Email Integration in NestJS with SendGrid

Email functionality is a crucial part of most web applications. Today, I'll show you how to easily integrate SendGrid email service into your NestJS application using @sologence/nest-js-email-sendgrid.

Why This Package?
🚀 Easy integration with NestJS applications
📧 Support for template-based emails, HTML, and plain text
🔒 Secure configuration with async options
🎭 Built-in email masking for secure logging
⚡ Type-safe email parameters

Getting Started
First, install the package:

npm install @sologence/nest-js-email-sendgrid
Enter fullscreen mode Exit fullscreen mode

Basic Setup
You can set up the module in two ways:

1. Simple Configuration

import { SendgridModule } from '@sologence/nest-js-email-sendgrid';

@Module({
  imports: [
    SendgridModule.register({
      apiKey: 'YOUR_SENDGRID_API_KEY',
      defaultFromEmail: 'your@email.com',
      masking: true // Enables email masking in logs
    }),
  ],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

2. Async Configuration (Recommended)

@Injectable()
export class WelcomeService {
  constructor(private readonly sendgridService: SendgridService) {}

  async sendWelcome(userEmail: string) {
    await this.sendgridService.sendEmailFromTemplate({
      to: userEmail,
      templateId: 'your-template-id',
      dynamicTemplateData: {
        name: 'John',
        activationLink: 'https://yourapp.com/activate'
      }
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

Custom HTML Emails

await sendgridService.sendEmailCustomHtmlBody({
  to: 'user@example.com',
  subject: 'Welcome!',
  html: '<h1>Welcome to our platform!</h1>'
});
Enter fullscreen mode Exit fullscreen mode

Plain Text Emails

await sendgridService.sendEmailCustomText({
  to: 'user@example.com',
  subject: 'Simple Notification',
  text: 'Your account has been updated.'
});
Enter fullscreen mode Exit fullscreen mode

Emails with S3 Attachments

await sendgridService.sendEmailWithS3Attachment({
  to: 'user@example.com',
  subject: 'Your Document',
  text: 'Please find your document attached.',
  url: 'https://your-s3-bucket.amazonaws.com/document.pdf',
  fileName: 'report.pdf'
});
Enter fullscreen mode Exit fullscreen mode

Error Handling
The package provides proper error handling:

try {
  await sendgridService.sendEmailFromTemplate(params);
} catch (error) {
  if (error instanceof BadRequestException) {
    // Handle validation errors
  }
  // Handle other errors
}
Enter fullscreen mode Exit fullscreen mode

Best Practices
Always use environment variables for sensitive data like API keys
Enable email masking in production for security
Use template IDs for consistent email styling
Implement proper error handling
Use async configuration for better flexibility
Conclusion
The @sologence/nest-js-email-sendgrid package makes it straightforward to integrate SendGrid with your NestJS application. With features like email masking, S3 attachments support, and type-safe parameters, it provides a robust solution for handling email functionality.

You can find more details in the GitHub repository or install it directly from npm.

Happy coding! 🚀

Top comments (2)

Collapse
 
talent_poolservices_6b6e profile image
Talent Pool Services

perfect package for nest js and sendgrid integration. Thanks for sharing

Collapse
 
rahul_soni_cfc330eda1c08e profile image
Rahul Soni

Perfect, awesome!!!