0

Tích hợp Email đơn giản trong NestJS với SendGrid

Chức năng email là một phần quan trọng của hầu hết các ứng dụng web. Hôm nay, tôi sẽ chỉ cho bạn cách dễ dàng tích hợp dịch vụ email SendGrid vào ứng dụng NestJS của bạn bằng cách sử dụng gói @sologence/nest-js-email-sendgrid.

Tại sao lại là gói này?

  • Tích hợp dễ dàng với các ứng dụng NestJS
  • Hỗ trợ email dựa trên mẫu, HTML và văn bản thuần túy
  • Cấu hình an toàn với các tùy chọn không đồng bộ
  • Che dấu email tích hợp để ghi nhật ký an toàn
  • Tham số email an toàn về kiểu

Bắt đầu cài đặt

Trước tiên, hãy cài đặt gói:

npm install @sologence/nest-js-email-sendgrid

Bạn có thể thiết lập mô-đun theo hai cách:

1. Cấu hình đơn giản

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. Cấu hình không đồng bộ (Khuyến nghị)

@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'
      }
    });
  }
}

Email HTML tùy chỉnh

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

Email văn bản thuần túy

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

Email có tệp đính kèm S3

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'
});

Xử lý lỗi

Gói này cung cấp cách xử lý lỗi phù hợp:

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

Kết luận

Gói @sologence/nest-js-email-sendgrid giúp tích hợp SendGrid với ứng dụng NestJS của bạn một cách dễ dàng. Với các tính năng như che giấu email, hỗ trợ tệp đính kèm S3 và tham số an toàn kiểu, gói này cung cấp giải pháp mạnh mẽ để xử lý chức năng email.

Hy vọng nó sẽ giúp ích cho các bạn!


All rights reserved

Bình luận

Đăng nhập để bình luận
Avatar
0
Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí