Created
April 8, 2024 14:16
-
-
Save alexanderson1993/8efab4948d11cb81421d353e679eade0 to your computer and use it in GitHub Desktop.
Fetch-based email sending using SES - perfect for Cloudflare and other non-Node.js runtimes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { AwsClient } from "aws4fetch"; | |
const sesEndpoint = "email.us-east-1.amazonaws.com"; | |
export function makeEmailSender({ | |
accessKeyId, | |
secretAccessKey, | |
defaultFromAddress, | |
}: { | |
accessKeyId: string; | |
secretAccessKey: string; | |
defaultFromAddress: string; | |
}) { | |
const awsClient = | |
accessKeyId && secretAccessKey | |
? new AwsClient({ | |
accessKeyId, | |
secretAccessKey, | |
}) | |
: null; | |
return async function sendEmail({ | |
to, | |
subject, | |
html, | |
text, | |
from, | |
}: { | |
to: string | string[]; | |
subject: string; | |
html?: string; | |
text: string; | |
from?: string; | |
}) { | |
if (!awsClient) { | |
console.log({ to, subject, text, html, from }); | |
return; | |
} | |
await awsClient.fetch(`https://${sesEndpoint}/v2/email/outbound-emails`, { | |
method: "POST", | |
headers: { "Content-Type": "application/json" }, | |
body: JSON.stringify({ | |
Content: { | |
Simple: { | |
Subject: { Data: subject }, | |
Body: { | |
...(html | |
? { | |
Html: { | |
Data: html, | |
}, | |
} | |
: null), | |
Text: { | |
Data: text, | |
}, | |
}, | |
}, | |
}, | |
Destination: { | |
ToAddresses: Array.isArray(to) ? to : [to], | |
}, | |
FromEmailAddress: from || defaultFromAddress, | |
}), | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment