93 lines
2.2 KiB
TypeScript
93 lines
2.2 KiB
TypeScript
import { SESv2Client, SendEmailCommand } from "@aws-sdk/client-sesv2";
|
|
import { UseSend } from "usesend-js";
|
|
|
|
const apiKey = process.env.USESEND_API_KEY;
|
|
const baseUrl = process.env.USESEND_BASE_URL;
|
|
const awsAccessKey = process.env.AWS_ACCESS_KEY;
|
|
const awsSecretKey = process.env.AWS_SECRET_KEY;
|
|
const awsRegion = process.env.AWS_DEFAULT_REGION;
|
|
|
|
export const usesend = apiKey ? new UseSend(apiKey, baseUrl) : null;
|
|
const sesClient =
|
|
awsAccessKey && awsSecretKey && awsRegion
|
|
? new SESv2Client({
|
|
region: awsRegion,
|
|
credentials: {
|
|
accessKeyId: awsAccessKey,
|
|
secretAccessKey: awsSecretKey,
|
|
},
|
|
})
|
|
: null;
|
|
|
|
export const FROM_EMAIL =
|
|
process.env.USESEND_FROM_EMAIL || "info@rockymountainvending.com";
|
|
export const TO_EMAIL =
|
|
process.env.CONTACT_FORM_TO_EMAIL || "info@rockymountainvending.com";
|
|
|
|
function htmlToText(html: string) {
|
|
return html
|
|
.replace(/<style[\s\S]*?<\/style>/gi, " ")
|
|
.replace(/<script[\s\S]*?<\/script>/gi, " ")
|
|
.replace(/<[^>]+>/g, " ")
|
|
.replace(/ /g, " ")
|
|
.replace(/&/g, "&")
|
|
.replace(/</g, "<")
|
|
.replace(/>/g, ">")
|
|
.replace(/\s+/g, " ")
|
|
.trim();
|
|
}
|
|
|
|
export function isEmailConfigured() {
|
|
return Boolean(usesend || sesClient);
|
|
}
|
|
|
|
export async function sendTransactionalEmail({
|
|
to,
|
|
subject,
|
|
html,
|
|
replyTo,
|
|
}: {
|
|
to: string;
|
|
subject: string;
|
|
html: string;
|
|
replyTo?: string;
|
|
}) {
|
|
if (usesend) {
|
|
return usesend.emails.send({
|
|
from: FROM_EMAIL,
|
|
to,
|
|
subject,
|
|
html,
|
|
...(replyTo ? { replyTo } : {}),
|
|
});
|
|
}
|
|
|
|
if (sesClient) {
|
|
return sesClient.send(
|
|
new SendEmailCommand({
|
|
FromEmailAddress: FROM_EMAIL,
|
|
Destination: {
|
|
ToAddresses: [to],
|
|
},
|
|
ReplyToAddresses: replyTo ? [replyTo] : undefined,
|
|
Content: {
|
|
Simple: {
|
|
Subject: {
|
|
Data: subject,
|
|
},
|
|
Body: {
|
|
Html: {
|
|
Data: html,
|
|
},
|
|
Text: {
|
|
Data: htmlToText(html),
|
|
},
|
|
},
|
|
},
|
|
},
|
|
})
|
|
);
|
|
}
|
|
|
|
throw new Error("No email transport is configured");
|
|
}
|