email.service.ts47 lines, 1.5 KB
| 1 | import { Resend } from "resend"; |
| 2 | import { verificationEmailTemplate } from "../templates/emails/verification.template"; |
| 3 | import logger from "../utils/logger"; |
| 4 | import { AppError } from "../utils/errors"; |
| 5 | import { StatusCodes } from "http-status-codes"; |
| 6 | import { welcomeEmailTemplate } from "../templates/emails/welcome.template"; |
| 7 | |
| 8 | export class EmailService { |
| 9 | private static readonly resend = new Resend(process.env.RESEND_API_KEY || ""); |
| 10 | private static readonly FROM_EMAIL = "onboarding@resend.dev"; |
| 11 | |
| 12 | static async sendVerificationEmail(email: string, token: string) { |
| 13 | try { |
| 14 | const verificationUrl = `${process.env.FRONTEND_URL}/auth/verify-email?token=${token}`; |
| 15 | |
| 16 | await this.resend.emails.send({ |
| 17 | from: this.FROM_EMAIL, |
| 18 | to: email, |
| 19 | subject: "Verify your email", |
| 20 | html: verificationEmailTemplate(verificationUrl), |
| 21 | }); |
| 22 | } catch (error) { |
| 23 | logger.error(`Error sending verification email: ${error}`); |
| 24 | throw new AppError( |
| 25 | StatusCodes.INTERNAL_SERVER_ERROR, |
| 26 | "Failed to send verification email" |
| 27 | ); |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | static async sendWelcomeEmail(email: string, name: string) { |
| 32 | try { |
| 33 | await this.resend.emails.send({ |
| 34 | from: this.FROM_EMAIL, |
| 35 | to: email, |
| 36 | subject: "Welcome to our app", |
| 37 | html: welcomeEmailTemplate(name || "There"), |
| 38 | }); |
| 39 | } catch (error) { |
| 40 | logger.error(`Error sending welcome email: ${error}`); |
| 41 | throw new AppError( |
| 42 | StatusCodes.INTERNAL_SERVER_ERROR, |
| 43 | "Failed to send welcome email" |
| 44 | ); |
| 45 | } |
| 46 | } |
| 47 | } |