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

149 lines
4.0 KiB
TypeScript

import nodemailer from "npm:nodemailer@^6.9.16";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers":
"authorization, x-client-info, apikey, content-type",
};
interface EmailAttachmentPayload {
filename: string;
contentBase64: string;
contentType?: string;
}
interface SendEmailRequest {
to?: string;
subject?: string;
text?: string;
html?: string;
replyTo?: string;
account?: string;
attachments?: EmailAttachmentPayload[];
}
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 isAssistenza = body.account?.trim().toLowerCase() === "assistenza";
const smtpUser = isAssistenza
? (Deno.env.get("SMTP_USER_ASSISTENZA") ?? "assistenza@catelli.it")
: (Deno.env.get("SMTP_USER") ?? "ordini@catelli.it");
const smtpPass = isAssistenza
? (Deno.env.get("SMTP_PASS_ASSISTENZA") ?? Deno.env.get("SMTP_PASS"))
: Deno.env.get("SMTP_PASS");
const smtpFrom = isAssistenza
? (Deno.env.get("SMTP_FROM_ASSISTENZA") ??
`Assistenza Catelli <${smtpUser}>`)
: (Deno.env.get("SMTP_FROM") ?? `Ordini Catelli <${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 attachments = Array.isArray(body.attachments)
? body.attachments
.filter((a) => a && a.filename && a.contentBase64)
.map((a) => ({
filename: a.filename,
content: a.contentBase64,
encoding: "base64",
contentType: a.contentType ?? "application/pdf",
}))
: undefined;
const info = await transporter.sendMail({
from: smtpFrom,
to,
subject,
text: text || undefined,
html: html || undefined,
replyTo: replyTo || undefined,
attachments: attachments && attachments.length > 0 ? attachments : 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" },
},
);
}
});