64 lines
1.5 KiB
TypeScript
64 lines
1.5 KiB
TypeScript
/** src/lib/server/resend.ts
|
|
* AUTHOR: Neil Clack
|
|
* EMAIL: nclack@radiantwavetech.com
|
|
* DATE: 07/06/2027
|
|
*
|
|
* A server side library and client for Resend
|
|
* Includes the Resend client, as well as functions
|
|
* for different email scenarios.
|
|
*
|
|
*/
|
|
import { Resend } from 'resend';
|
|
import { env } from '$env/dynamic/private';
|
|
|
|
let _resend: Resend;
|
|
|
|
function getResend(): Resend {
|
|
if (!_resend) {
|
|
_resend = new Resend(env.RESEND_API_KEY);
|
|
}
|
|
return _resend;
|
|
}
|
|
|
|
/**
|
|
* Send a transactional email using a Resend-hosted template.
|
|
*
|
|
* @example
|
|
* await sendMail({
|
|
* to: 'jane@example.com',
|
|
* templateId: 'tmpl_abc123', // required — Resend template id or alias
|
|
* subject: 'Your license key is ready', // optional — defaults to 'Template Email'
|
|
* data: { // optional — template variables
|
|
* firstName: 'Jane',
|
|
* licenseKey: 'RWT-7X9K-2M4Q'
|
|
* }
|
|
* });
|
|
*
|
|
* @returns The Resend API response data on success.
|
|
* @throws {Error} If the Resend API call fails.
|
|
*/
|
|
export async function sendMail(options: {
|
|
to: string;
|
|
subject?: string;
|
|
templateId: string;
|
|
data?: Record<string, string | number>;
|
|
}) {
|
|
const { to, subject, templateId, data } = options;
|
|
|
|
const result = await getResend().emails.send({
|
|
from: env.EMAIL_FROM,
|
|
to: [to],
|
|
subject: subject ?? 'Template Email',
|
|
template: {
|
|
id: templateId,
|
|
variables: data ?? {}
|
|
}
|
|
});
|
|
|
|
if (result.error) {
|
|
throw new Error(result.error.message);
|
|
}
|
|
|
|
return result.data;
|
|
}
|