Add email via Resend
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
/** 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 { RESEND_API_KEY, EMAIL_FROM, RESEND_TEMPLATE_ID } from '$env/static/private';
|
||||
|
||||
export const resend = new Resend(RESEND_API_KEY);
|
||||
|
||||
/**
|
||||
* Send a transactional email using a Resend-hosted template.
|
||||
*
|
||||
* @example
|
||||
* await sendMail({
|
||||
* to: 'jane@example.com',
|
||||
* templateId: 'tmpl_abc123', // optional — defaults to RESEND_TEMPLATE_ID
|
||||
* 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 resend.emails.send({
|
||||
from: EMAIL_FROM,
|
||||
to: [to],
|
||||
subject: subject ?? 'Template Email',
|
||||
template: {
|
||||
id: templateId ?? RESEND_TEMPLATE_ID,
|
||||
variables: data ?? {}
|
||||
}
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
throw new Error(result.error.message);
|
||||
}
|
||||
|
||||
return result.data;
|
||||
}
|
||||
Reference in New Issue
Block a user