1.0.5 • Published 2 months ago

@sologence/nest-js-email-sendgrid v1.0.5

Weekly downloads
-
License
ISC
Repository
github
Last release
2 months ago

NestJS SendGrid Integration

A robust NestJS module for seamless SendGrid email integration, providing an easy-to-use interface for sending emails using SendGrid's API.

Features

  • 🚀 Easy integration with NestJS applications
  • 📧 Support for template-based emails
  • 🎨 Custom HTML and plain text emails
  • ⚡ Type-safe email parameters
  • 🔒 Secure API key configuration
  • 🎭 Email masking support for secure logging

Installation

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

Quick Start

  1. Import the module in your app.module.ts. You can use either synchronous registration or async registration:

Synchronous Registration

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

@Module({
  imports: [
    SendgridModule.register({
      apiKey: 'YOUR_SENDGRID_API_KEY',
      defaultFromEmail: 'your@email.com',
      isGlobal: true, // optional, defaults to false
      masking: true //to enable masking while logging the email default false
    }),
  ],
})
export class AppModule {}

Asynchronous Registration

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

@Module({
  imports: [
    SendgridModule.registerAsync({
      imports: [ConfigModule], // optional: import modules that are needed for config
      useFactory: async (configService: ConfigService) => ({
        apiKey: configService.get('SENDGRID_API_KEY'),
        defaultFromEmail: configService.get('SENDGRID_FROM_EMAIL'),
        isGlobal: true, // optional, defaults to false
        masking: true //to enable masking while logging the email default false
      }),
      inject: [ConfigService], // optional: services to inject into useFactory
    }),
  ],
})
export class AppModule {}
  1. Inject and use the service in your components:
import { SendgridService } from '@sologence/nest-js-email-sendgrid';

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

  async sendWelcomeEmail(to: string) {
    await this.sendgridService.sendEmailFromTemplate({
      to,
      from: 'your@email.com',
      templateId: 'your-template-id',
      dynamicTemplateData: {
        name: 'John Doe',
      },
    });
  }
}

API Reference

SendgridService Methods

sendEmailFromTemplate(params: EmailParams)

Send emails using SendGrid templates.

await sendgridService.sendEmailFromTemplate({
  to: 'recipient@example.com',
  from: 'sender@example.com',
  templateId: 'template-id',
  dynamicTemplateData: {
    // Your template variables
  },
});

sendEmailCustomHtmlBody(params: EmailParams)

Send emails with custom HTML content.

await sendgridService.sendEmailCustomHtmlBody({
  to: 'recipient@example.com',
  from: 'sender@example.com',
  subject: 'Hello',
  html: '<h1>Hello World!</h1>',
});

sendEmailCustomText(params: EmailParams)

Send plain text emails.

await sendgridService.sendEmailCustomText({
  to: 'recipient@example.com',
  from: 'sender@example.com',
  subject: 'Hello',
  text: 'Hello World!',
});

Sending Emails with S3 Attachments

The module now supports sending emails with attachments directly from S3 URLs using Nodemailer transport:

// Inject the service
constructor(private readonly sendgridService: SendgridService) {}

// Send email with S3 attachment
await this.sendgridService.sendEmailWithS3Attachment({
  to: 'recipient@example.com',
  from: 'sender@example.com', // optional if defaultFromEmail is set
  subject: 'Document Attached',
  text: 'Please find the attached document',
  url: 'https://your-bucket.s3.amazonaws.com/path/to/file',
  fileName: 'document.pdf' // optional, defaults to 'attachment'
});

S3 Attachment Parameters

ParameterTypeRequiredDescription
tostring | string[]YesRecipient email address(es)
fromstringNoSender email address (falls back to defaultFromEmail)
subjectstringYesEmail subject
textstringYesEmail body text
urlstringYesFull URL to the S3 file
fileNamestringNoCustom filename for the attachment

Response

The method returns a Promise that resolves to the Nodemailer send result object.

Configuration Options

OptionTypeDescription
apiKeystringYour SendGrid API key
defaultFromstring?Default sender email address
sandboxModeboolean?Enable SendGrid sandbox mode
maskingboolean?Enable email masking in logs

Error Handling

The service throws typed errors that you can catch and handle:

try {
  await sendgridService.sendEmailFromTemplate(params);
} catch (error) {
  if (error instanceof SendGridError) {
    // Handle SendGrid specific errors
  }
  // Handle other errors
}

Contributing

We welcome contributions! Please feel free to submit a Pull Request.

License

MIT License - see the LICENSE file for details.

Support

For support, please create an issue in the GitHub repository or contact our support team.

1.0.5

2 months ago

1.0.4

7 months ago

1.0.3

7 months ago

1.0.2

7 months ago

1.0.1

7 months ago

1.0.0

7 months ago