Files
webshop/shop/utils/mail.ts
DanielS b2656345e8
All checks were successful
Staging Build / build (push) Successful in 2m34s
feat: Send email confirmation with PDF attachment upon successful order
2026-06-25 02:47:03 +02:00

73 lines
1.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// utils/mail.ts simple wrapper around nodemailer
import nodemailer from 'nodemailer';
import { createAdminClient } from '@/lib/supabase/admin';
/**
* Send an email using database-configured SMTP settings (or environment variable fallback).
* @param to Recipient address
* @param subject Subject line
* @param text Plaintext body
* @param html Optional HTML body
*/
export async function sendMail({
to,
subject,
text,
html,
attachments,
}: {
to: string;
subject: string;
text: string;
html?: string;
attachments?: {
filename: string;
content: Buffer | string;
contentType?: string;
}[];
}) {
// Query custom SMTP settings from database
const supabase = createAdminClient();
const { data: dbSettings } = await supabase
.from('settings')
.select('*')
.eq('id', 'smtp')
.maybeSingle();
// Resolve config from DB or environment variables
const host = dbSettings?.host || process.env.SMTP_HOST;
const port = dbSettings?.port ? Number(dbSettings.port) : Number(process.env.SMTP_PORT);
const secure = dbSettings
? !!dbSettings.secure
: (process.env.SMTP_SECURE === 'true' || process.env.SMTP_SECURE === '1');
const user = dbSettings?.user || process.env.SMTP_USER;
const pass = dbSettings?.pass || process.env.SMTP_PASS;
if (!host || !user) {
throw new Error('SMTP host and user must be configured (either in settings database table or environment variables).');
}
// Create transporter dynamically on send request
const transporter = nodemailer.createTransport({
host,
port,
secure,
auth: {
user,
pass,
},
});
const info = await transporter.sendMail({
from: user,
to,
subject,
text,
html,
attachments,
});
return info;
}