Files
flux/supabase/functions/send-email/index.ts
T

121 lines
3.0 KiB
TypeScript

import nodemailer from "nodemailer";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers":
"authorization, x-client-info, apikey, content-type",
};
interface SendEmailRequest {
to?: string;
subject?: string;
text?: string;
html?: string;
replyTo?: string;
}
Deno.serve(async (req) => {
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
try {
const body = (await req.json()) as SendEmailRequest;
const to = body.to?.trim() ?? "";
const subject = body.subject?.trim() ?? "";
const text = body.text?.trim() ?? "";
const html = body.html?.trim();
const replyTo = body.replyTo?.trim();
if (!to) {
return new Response(
JSON.stringify({
success: false,
error: "Indirizzo email destinatario mancante.",
}),
{
status: 400,
headers: { ...corsHeaders, "Content-Type": "application/json" },
},
);
}
if (!subject || (!text && !html)) {
return new Response(
JSON.stringify({
success: false,
error: "Oggetto e contenuto dell'email sono obbligatori.",
}),
{
status: 400,
headers: { ...corsHeaders, "Content-Type": "application/json" },
},
);
}
const smtpHost = Deno.env.get("SMTP_HOST") ?? "stalwart.catelli.it";
const smtpPort = Number(Deno.env.get("SMTP_PORT") ?? "465");
const smtpUser = Deno.env.get("SMTP_USER") ?? "ordini@catelli.it";
const smtpPass = Deno.env.get("SMTP_PASS");
const smtpFrom = Deno.env.get("SMTP_FROM") ?? `Ordini <${smtpUser}>`;
if (!smtpPass) {
return new Response(
JSON.stringify({
success: false,
error: "Credenziali SMTP non configurate sul server (SMTP_PASS).",
}),
{
status: 500,
headers: { ...corsHeaders, "Content-Type": "application/json" },
},
);
}
const transporter = nodemailer.createTransport({
host: smtpHost,
port: smtpPort,
secure: smtpPort === 465,
auth: {
user: smtpUser,
pass: smtpPass,
},
});
const info = await transporter.sendMail({
from: smtpFrom,
to,
subject,
text: text || undefined,
html: html || undefined,
replyTo: replyTo || undefined,
});
return new Response(
JSON.stringify({
success: true,
to,
messageId: info.messageId,
}),
{
status: 200,
headers: { ...corsHeaders, "Content-Type": "application/json" },
},
);
} catch (error) {
const message =
error instanceof Error ? error.message : "Errore sconosciuto invio email";
console.error("send-email error:", message);
return new Response(
JSON.stringify({
success: false,
error: `Errore invio email: ${message}`,
}),
{
status: 500,
headers: { ...corsHeaders, "Content-Type": "application/json" },
},
);
}
});