This commit is contained in:
90
utils/sweego.ts
Normal file
90
utils/sweego.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
interface EmailTemplate {
|
||||
subject: string;
|
||||
template: JSX.Element;
|
||||
}
|
||||
|
||||
const SWEEGO_API_URL = 'https://api.sweego.io/send';
|
||||
|
||||
const renderTemplate = async (template: JSX.Element): Promise<string> => {
|
||||
const { renderToStaticMarkup } = await import('react-dom/server');
|
||||
const html = renderToStaticMarkup(template);
|
||||
return `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
</head>
|
||||
<body style="margin: 0; padding: 0; background-color: #f4f4f5;">
|
||||
${html}
|
||||
</body>
|
||||
</html>`;
|
||||
};
|
||||
|
||||
export async function sender(
|
||||
recipients: string[],
|
||||
{ subject, template }: EmailTemplate
|
||||
): Promise<boolean> {
|
||||
if (!process.env.SWEEGO_API_KEY) {
|
||||
throw new Error('SWEEGO_API_KEY is not set');
|
||||
}
|
||||
if (!process.env.SWEEGO_FROM) {
|
||||
throw new Error('SWEEGO_FROM is not set');
|
||||
}
|
||||
|
||||
if (recipients.length === 0) {
|
||||
console.info(`${subject} email skipped for having zero recipients`);
|
||||
return true;
|
||||
}
|
||||
|
||||
const htmlContent = await renderTemplate(template);
|
||||
const fromName = process.env.NEXT_PUBLIC_BRAND_NAME || 'Newsletter';
|
||||
|
||||
let successCount = 0;
|
||||
let failCount = 0;
|
||||
|
||||
for (const recipient of recipients) {
|
||||
try {
|
||||
const response = await fetch(SWEEGO_API_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Api-Key': process.env.SWEEGO_API_KEY
|
||||
},
|
||||
body: JSON.stringify({
|
||||
channel: 'email',
|
||||
provider: 'sweego',
|
||||
recipients: [{ email: recipient }],
|
||||
from: {
|
||||
name: fromName,
|
||||
email: process.env.SWEEGO_FROM
|
||||
},
|
||||
subject,
|
||||
'message-html': htmlContent,
|
||||
headers: {
|
||||
'List-Unsubscribe': `<mailto:${process.env.NEXT_PUBLIC_BRAND_EMAIL}>`
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.text();
|
||||
console.error(
|
||||
`Failed to send to ${recipient}: ${response.status} ${error}`
|
||||
);
|
||||
failCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
successCount++;
|
||||
} catch (error) {
|
||||
console.error(`Failed to send to ${recipient}:`, error);
|
||||
failCount++;
|
||||
}
|
||||
}
|
||||
|
||||
console.info(
|
||||
`${subject} email: ${successCount} sent, ${failCount} failed out of ${recipients.length} recipients`
|
||||
);
|
||||
|
||||
return successCount > 0;
|
||||
}
|
||||
Reference in New Issue
Block a user