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
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 {}
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'
}
});
}
}
Custom HTML Emails
await sendgridService.sendEmailCustomHtmlBody({
to: 'user@example.com',
subject: 'Welcome!',
html: '<h1>Welcome to our platform!</h1>'
});
Plain Text Emails
await sendgridService.sendEmailCustomText({
to: 'user@example.com',
subject: 'Simple Notification',
text: 'Your account has been updated.'
});
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'
});
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
}
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 (0)