strapi-plugin-email-brevo
Version:
Strapi v5 plugin to send emails via Brevo (Sendinblue) HTTP API
75 lines (66 loc) • 2.26 kB
JavaScript
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, // "Sender Alex <senderalex@example.com>"
to, // "recipient@example.com" or array
subject,
html,
text,
replyTo,
} = 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 }];
const payload = {
sender: {
name: senderName,
email: senderEmail,
},
to: formattedTo,
subject,
htmlContent: html,
textContent: text,
replyTo: replyTo ? { email: replyTo } : undefined,
};
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;
}
},
};
},
};