|
| 1 | +import { MailDriver } from './interfaces/mail-driver.interface'; |
| 2 | +import { ResendConfig } from '../interfaces'; |
| 3 | +import { Resend } from 'resend'; |
| 4 | +import { MailMessage } from '../interfaces/mail.message'; |
| 5 | +import { Logger } from '@nestjs/common'; |
| 6 | +import { mailLogName } from '../mail.utils'; |
| 7 | + |
| 8 | +export class ResendDriver implements MailDriver { |
| 9 | + private readonly logger = new Logger(mailLogName(ResendDriver.name)); |
| 10 | + private readonly resendClient: Resend; |
| 11 | + |
| 12 | + constructor(config: ResendConfig) { |
| 13 | + this.logger.debug(`TOKEN ${config.resendApiToken}`); |
| 14 | + this.resendClient = new Resend(config.resendApiToken); |
| 15 | + } |
| 16 | + |
| 17 | + private formatEmailAddress(email: string): string { |
| 18 | + if (email.includes('<') && email.includes('>')) { |
| 19 | + const matches = email.match(/<(.+)>/); |
| 20 | + if (matches && matches[1]) { |
| 21 | + return matches[1]; |
| 22 | + } |
| 23 | + } |
| 24 | + return email; |
| 25 | + } |
| 26 | + |
| 27 | + async sendMail(message: MailMessage): Promise<void> { |
| 28 | + try { |
| 29 | + const fromEmail = this.formatEmailAddress(message.from); |
| 30 | + this.logger.debug(`Attempting to send mail from ${fromEmail}`); |
| 31 | + |
| 32 | + const { data, error } = await this.resendClient.emails.send({ |
| 33 | + from: fromEmail, |
| 34 | + to: message.to, |
| 35 | + subject: message.subject, |
| 36 | + text: message.text, |
| 37 | + html: message.html, |
| 38 | + }); |
| 39 | + |
| 40 | + if (error) { |
| 41 | + this.logger.error(`Failed to send mail: ${error.message}`); |
| 42 | + throw new Error(error.message); |
| 43 | + } |
| 44 | + |
| 45 | + this.logger.debug(`Email sent successfully. ID: ${data?.id}`); |
| 46 | + } catch (err) { |
| 47 | + this.logger.error(`Failed to send mail: ${err}`); |
| 48 | + throw err; |
| 49 | + } |
| 50 | + } |
| 51 | +} |
0 commit comments