From 2480fc451e7e2fec6a07c9eb6fcf8194557101c2 Mon Sep 17 00:00:00 2001 From: Mark Bruderer Date: Sat, 19 Apr 2025 22:03:16 +0200 Subject: [PATCH] feat: add brevo as a provider. --- src/index.ts | 4 ++++ src/services/brevo.ts | 49 ++++++++++++++++++++++++++++++++++++++ src/types/email-options.ts | 3 ++- 3 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 src/services/brevo.ts diff --git a/src/index.ts b/src/index.ts index e435d1d..f3b1b94 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,6 +4,7 @@ import { ResendService } from "./services/resend"; import { SendGridService } from "./services/sendgrid"; import { MailgunService } from "./services/mailgun"; import { ZeptoMailService } from "./services/zeptomail"; +import { BrevoService } from "./services/brevo"; import type { EmailProvider } from "./types/email-options"; import type { EmailService } from "./types/email-service"; @@ -33,6 +34,9 @@ export function useEmail(provider: EmailProvider): EmailService { case "zeptomail": { return new ZeptoMailService(); } + case "brevo": { + return BrevoService(); + } default: { throw new Error(`Unsupported email provider: ${provider}`); } diff --git a/src/services/brevo.ts b/src/services/brevo.ts new file mode 100644 index 0000000..1e36dff --- /dev/null +++ b/src/services/brevo.ts @@ -0,0 +1,49 @@ +import { ofetch as $fetch } from "ofetch"; +import type { EmailOptions } from "../types/email-options"; +import type { EmailService } from "../types/email-service"; + +/** + * Email service implementation for Mailgun + */ +export const BrevoService = (): EmailService => { + const BREVO_API_KEY = process.env.BREVO_API_KEY; + const BREVO_API_URL = "https://api.brevo.com/v3/smtp/email"; + + const send = async (emailOptions: EmailOptions): Promise => { + if (!BREVO_API_KEY) { + throw new Error("Brevo API key is missing"); + } + + const { to, from, subject, text, html } = emailOptions; + if (!to || !from || (!text && !html)) { + throw new Error("Required email fields are missing"); + } + + const payload = { + sender: { email: from }, + to: Array.isArray(to) + ? to.map((email) => ({ email })) + : [{ email: to }], + subject: subject, + textContent: text, + htmlContent: html, + }; + + try { + await $fetch(BREVO_API_URL, { + method: "POST", + headers: { + "api-key": BREVO_API_KEY, + "Content-Type": "application/json", + }, + body: JSON.stringify(payload), + }); + console.log("Email sent via Brevo"); + } catch (error) { + console.error("Failed to send email with Brevo:", error); + throw new Error("Email sending failed with Brevo"); + } + }; + + return { send }; +}; diff --git a/src/types/email-options.ts b/src/types/email-options.ts index 62626af..f322eb0 100644 --- a/src/types/email-options.ts +++ b/src/types/email-options.ts @@ -18,4 +18,5 @@ export type EmailProvider = | "sendgrid" | "postmark" | "mailgun" - | "zeptomail"; + | "zeptomail" + | "brevo";