UNPKG

strapi-plugin-email-brevo

Version:

Strapi v5 plugin to send emails via Brevo (Sendinblue) HTTP API

88 lines (77 loc) 2.67 kB
"use strict"; const axios = require("axios"); module.exports = { init: (providerOptions = {}, settings = {}) => { const apiKey = providerOptions.apiKey; const apiUrl = "https://api.brevo.com/v3"; return { async send(options) { try { const { from, to, subject, html, text, replyTo, attachments, // 👈 attachment support added } = options; // Parse sender name and email let senderName = settings.defaultSenderName || "Sender"; let senderEmail = settings.defaultSenderEmail || "noreply@example.com"; if (from?.includes("<")) { const nameMatch = from.match(/(.*?)</); const emailMatch = from.match(/<(.*?)>/); senderName = nameMatch ? nameMatch[1].trim() : senderName; senderEmail = emailMatch ? emailMatch[1].trim() : senderEmail; } else if (typeof from === "string") { senderEmail = from; } // Format 'to' as required by Brevo: array of { email, name? } const formattedTo = Array.isArray(to) ? to.map((email) => typeof email === "object" ? { email: email.email, name: email.name || undefined } : { email } ) : [{ email: to }]; // Format attachments for Brevo API (base64 string + filename) const formattedAttachments = Array.isArray(attachments) ? attachments.map((att) => ({ name: att.filename, content: att.content, // must be base64-encoded string })) : undefined; // Prepare payload const payload = { sender: { name: senderName, email: senderEmail, }, to: formattedTo, subject, htmlContent: html, textContent: text, replyTo: replyTo ? { email: replyTo } : undefined, attachment: formattedAttachments, }; const response = await axios.post(`${apiUrl}/smtp/email`, payload, { headers: { accept: "application/json", "content-type": "application/json", "api-key": apiKey, }, }); return response.status === 201 || response.status === 200; } catch (err) { console.error( "❌ Brevo send error:", err.response?.data || err.message ); return false; } }, }; }, };